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))
}
}

--

--

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