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)

--

--

--

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

Recommended from Medium

Default arguments in Swift

Sketch Filter in iOS App Using Swift

How to Log and Toast (like Android) in iOS!

First view of iOS tutorial in Swift (an Android Developer view)

How to extract functionality from your iOS legacy code

Use Swift Struct For Total Immutability

Custom back press handling in Dialog Fragments

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

Preventing merge conflicts with XcodeGen for your xcode project using xcodeGen and project.yml file

Struct, Class and Protocol in Swift

Swift: The different between try, try? and try!

How to securely handle the Third-party Keys in iOS?