REALLY Understanding Swift ‘some’ keyword (and Swift Opaque types, consequently)

struct IntegerNumber {
var value: Int
func printValue() {
print(“value: \(value)”)
}
}
struct FloatingPointNumber {
var value: Float
func printValue() {
print(“value: \(value)”)
}
}
protocol Number {
associatedtype T
var value: T { get } func printValue()
}
struct IntegerNumber: Number {
var value: Int
func printValue() {
print(“value is Integer \(value)”)
}
}
struct FloatingPointNumber: Number {
var value: Float
func printValue() {
print(“value is Floating point \(value)”)
}
}
// ERROR: protocol ‘Number’ can only be used as a generic constraint
// because it has Self or associated type requirements !!!!
var selectedNumber: Number = integerNumber //???????? CANNOT!!!!!
var selectedNumber: some Number = integerNumber // 1
// or
var selectedNumber: some Number = floatingNumber // 2
var selectedNumber: IntegerNumber = integerNumber // 1
// or
var selectedNumber: FloatingPointNumber = floatingNumber // 2
selectedNumber.printValue()
var selectedNumber: some Number = integerNumber//ERROR! the compiler substituted ‘some Number’ with type IntegerNumber!
selectedNumber = floatingNumber
var selectedNumber: sonme Number = floatingNumber// ERROR! the compiler substituted ‘some Number’ with type IntegerNumber!
selectedNumber = integerNumber
//ERROR! Function declares an opaque return type, but the return statements in its body do not have matching underlying typesfunc createNumber() -> some Number {
let num = arc4random() % 10
if num % 2 == 0 {
return IntegerNumber(value: 11)
} else {
return FloatingPointNumber(value: Float(num))
}
}
// THIS compiles
func createNumber() -> some Number {
let num = arc4random() % 10
if num % 2 == 0 {
return IntegerNumber(value: 11)
} else {
return IntegerNumber(value: Int(num))
}
}

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Using Swift’s CustomStringConvertible

Swift Part 9 — Working with UIAlertController

Create Your Own Backend for Swift using Charles

viewDidLoad() Vs. loadView()

How to create currency formatter in iOS

Accessibility technology and UI tests for iOS apps — practical guide (iOS Automation Trip 2)

First Class Functions in Swift

The Only UIStackView Guide You Will Ever Need

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Vijay Chandran Jayachandran

Vijay Chandran Jayachandran

Engineer

More from Medium

Every iOS developer should know these Xcode tricks

Is Swift the Objective Choice now?

MVVM-C Xcode Template to reduce development time

Singleton in Swift New