Monday, March 16, 2026
HomeiOS DevelopmentNewbie's information to fashionable generic programming in Swift

Newbie’s information to fashionable generic programming in Swift


Protocols (with related varieties)

In line with the Swift language information a protocol can outline a blueprint of strategies, properties and different necessities. It is fairly straightforward to pre-define properties and strategies utilizing a protocol, the syntax is fairly simple, the issue begins to happen after we begin to work with related varieties. The very first query that we have now to reply is that this: what are related varieties precisely?

An related sort is a generic placeholder for a particular sort. We do not know that sort till the protocol is being adopted and the precise sort is specified by the implementation.

protocol MyProtocol {
    associatedtype MyType
    
    var myVar: MyType { get }
    
    func take a look at()
}

extension MyProtocol {
    
    func take a look at() {
        print("is that this a take a look at?")
    }
}
struct MyIntStruct: MyProtocol {
    typealias MyType = Int
    
    var myVar: Int { 42 }
}

struct MyStringStruct: MyProtocol {
    let myVar = "Howdy, World!"
}

let foo = MyIntStruct()
print(foo.myVar)
foo.take a look at()

let bar = MyStringStruct()
print(bar.myVar)
bar.take a look at()

As you possibly can see, related MyType placeholder can have differing kinds, after we implement the protocol. Within the first case (MyIntStruct) we have now explicitly instructed the compiler – by utilizing a typealias – to make use of an Int sort, and within the second case (MyStringStruct) the Swift compiler is wise sufficient to determine the kind of the myVar primarily based on the supplied String worth.

After all we are able to explicitly write let myVar: String = "Howdy, World!" or use a computed property or an everyday variable, it actually would not matter. The important thing takeaway is that we have outlined the kind of the MyType placeholder after we applied the protocol utilizing the 2 struct. 🔑

You should utilize an related sort to function a generic placeholder object so you do not have to duplicate code if you happen to want help for a number of differing kinds.

Existentials (any)

Nice, our generic protocol has a default take a look at technique implementation that we are able to use on each objects, now this is the factor, I do not actually care concerning the sort that is going to implement my protocol, I simply wish to name this take a look at operate and use the protocol as a sort, can I do this? Effectively, in case you are utilizing Swift 5.6+ the reply is sure, in any other case…


let myObject: MyProtocol 


let gadgets: [MyProtocol]

I wager that you have seen this well-known error message earlier than. What the hell is occurring right here?

The reply is kind of easy, the compiler cannot determine the underlying related sort of the protocol implementations, since they are often differing kinds (or ought to I say: dynamic at runtime 🤔), anyway, it is not decided at compile time.

The most recent model of the Swift programming language solves this situation by introducing a brand new any key phrase, which is a type-erasing helper that can field the ultimate sort right into a wrapper object that can be utilized as an existential sort. Sounds sophisticated? Effectively it’s. 😅



let myObject: any MyProtocol 

let gadgets: [any MyProtocol] = [MyIntStruct(), MyStringStruct()]

for merchandise in gadgets {
    merchandise.take a look at()
}

Through the use of the any key phrase the system can create an invisible field sort that factors to the precise implementation, the field has the identical sort and we are able to name the shared interface capabilities on it.

  • any HiddenMyProtocolBox: MyProtocol — pointer —> MyIntStruct
  • any HiddenMyProtocolBox: MyProtocol — pointer —> MyStringStruct

This method permits us to place totally different protocol implementations with Self related sort necessities into an array and name the take a look at technique on each of the objects.

If you happen to actually wish to perceive how this stuff work, I extremely suggest to observe the Embrace Swift Generics WWDC22 session video. Your complete video is a gem. 💎

There may be yet another session referred to as Design protocol interfaces in Swift that you need to undoubtedly watch if you wish to study extra about generics.

From Swift 5.7 the any key phrase is necessary when creating an existential sort, it is a breaking change, however it’s for the higher good. I actually like how Apple tackled this situation and each the any and a few key phrases are actually useful, nonetheless understanding the variations may be arduous. 🤓

Opaque varieties (some)

An opaque sort can conceal the sort data of a worth. By default, the compiler can infer the underlying sort, however in case of a protocol with an related sort the generic sort information cannot be resolved, and that is the place the some key phrase and the opaque sort can assist.

The some key phrase was launched in Swift 5.1 and also you should be conversant in it if you happen to’ve used SwiftUI earlier than. First it was a return sort function solely, however with Swift 5.7 now you can use the some key phrase in operate parameters as properly.

import SwiftUI

struct ContentView: View {

    
    var physique: some View {
        Textual content("Howdy, World!")
    }
}

Through the use of the some key phrase you possibly can inform the compiler that you will work on a particular concrete sort quite than the protocol, this fashion the compiler can carry out extra optimizations and see the precise return sort. Because of this you will not have the ability to assign a special sort to a variable with a some ‘restriction’. 🧐

var foo: some MyProtocol = MyIntStruct()


foo = MyStringStruct()

Opaque varieties can be utilized to conceal the precise sort data, you could find extra nice code examples utilizing the linked article, however since my put up focuses on the generics, I would like to point out you one particular factor associated to this subject.

func instanceMyProtocol>(_ worth: T) {}

func instance(_ worth: T) the place T: MyProtocol {}

func instance(_ worth: some MyProtocol) {}

Consider or not, however the 3 capabilities above are equivalent. The primary one is a generic operate the place the T placeholder sort conforms to the MyProtocol protocol. The second describes the very same factor, however we’re utilizing the the place claues and this permits us to put additional restrictions on the related varieties if wanted. e.g. the place T: MyProtocol, T.MyType == Int. The third one makes use of the some key phrase to cover the sort permitting us to make use of something as a operate parameter that conforms to the protocol. This can be a new function in Swift 5.7 and it makes the generic syntax extra easy. 🥳

If you wish to learn extra concerning the variations between the some and any key phrase, you possibly can learn this text by Donny Wals, it is actually useful.

Main related varieties (Protocol)

To constraint opaque end result varieties you should utilize the the place clause, or alternatively we are able to ‘tag’ the protocol with a number of main related varieties. This can permit us to make additional constraints on the first related sort when utilizing some.

protocol MyProtocol {
    associatedtype MyType
    
    var myVar: MyType { get }
    
    func take a look at()
}



func instance(_ worth: some MyProtocol<Int>) {
    print("asdf")
}

If you wish to study extra about main related varieties, you need to learn Donny’s article too. 💡

Generics ()

Up to now we’ve not actually talked about the usual generic options of Swift, however we had been principally specializing in protocols, related varieties, existentials and opaque varieties. Fortuitously you write generic code in Swift with out the necessity to contain all of those stuff.

struct Bag {
    var gadgets: [T]
}

let bagOfInt = Bag<Int>(gadgets: [4, 2, 0])
print(bagOfInt.gadgets)

let bagOfString = Bag<String>(gadgets: ["a", "b", "c"])
print(bagOfString.gadgets)

This bag sort has a placeholder sort referred to as T, which may maintain any type of the identical sort, after we initialize the bag we explicitly inform which kind are we going to make use of. On this instance we have created a generic sort utilizing a struct, however you may as well use an enum, a category and even an actor, plus it is usually attainable to put in writing much more easy generic capabilities. 🧐

func myPrint(_ worth: T) {
    print(worth)
}

myPrint("howdy")
myPrint(69)

If you wish to study extra about generics you need to learn this text by Paul Hudson, it is a good introduction to generic programming in Swift. Since this text is extra about offering an introduction I do not wish to get into the extra superior stuff. Generics may be actually obscure, particularly if we contain protocols and the brand new key phrases.

I hope this text will make it easier to to grasp this stuff only a bit higher.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments