Understanding Swift protocol Associated types

struct IntegerNumber: Number {
var value: Int
func printValue() {
print(“Integer: \(value)”)
}
}
struct FloatingPointNumber: Number {
var value: Float
func printValue() {
print(“Float: \(value)”)
}
}
protocol Number {
func printValue()
}
struct IntegerNumber: Number {
var value: Int
func printValue() {
print(“Integer: \(value)”)
}
}
struct FloatingPointNumber: Number {
var value: Float
func printValue() {
print(“Float: \(value)”)
}
}
let number: Number = FloatingPointNumber(value: 0.0) // or IntegerNumber(value: 0)number.printValue()
protocol Number {
associatedtype NumberType
var value: NumberType { get } func printValue()
}
// FORM 1struct IntegerNumber: Number {
var value: Int // compiler decides NumberType is Int
func printValue() {
print(“Ingeger: \(value)”)
}
}
// FORM 2
struct FloatingPointNumber: Number {
typealias NumberType = Float // explicit definitition
var value: NumberType func printValue() {
print(“Float: \(value)”)
}
}
// ERROR: Protocol ‘Number’ can only be used as a generic constraint because it has Self or associated type requirements
let number: Number = FloatingPointNumber(value: 0.0)
let number: some Number = FloatingPointNumber(value: 0.0) // or IntegerNumber(value: 0)print(number.value)

--

--

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