I’m still getting used to Associated Types in Swift. Even though they’ve been around for a while, I first startingto understand them from this talk by @alexisgallagher .

Swift: Making the Associated Type Parameter Readable in Protocols

Swift: Making the Associated Type Parameter Readable in Protocols - 敏捷大拇指 - Swift: Making the Associated Type Parameter Readable in Protocols


So I was happy yesterday when I used them to sort of solve a common problem in iOS development: View Controller Data Injection with Storyboards and Segues in Swift .

I updated my blog post from yesterday, but my initial Protocol looked something like this:

[Swift] 纯文本查看 复制代码
protocol Injectable {
 
    associatedtype T
    func inject(thing: T)
    func assertDependencies()
}


Notice the thing ! Since each View Controller would be injected with something specific – it could be text-based or number-based or array-based, anything! I didn’t know how to name the parameter. So thing seemed like the most fitting parameter name.

The implementation was something like this then:

[Swift] 纯文本查看 复制代码
func inject(thing: T) {
    textDependency = thing
}


I didn’t exactly like the whole thing here – it’s not that great with readability. So this morning, I though of a crazy solution for this, tried it out, and it actually worked!

[Swift] 纯文本查看 复制代码
protocol Injectable {
    associatedtype T
 
    // instead of thing, use _
    func inject(_: T)
}


Instead of using thing , I leave the parameter name blank in the protocol!

Apparently, this now let’s me name the parameter anything I want in the implementation!

[Swift] 纯文本查看 复制代码
class MyStringDependencyViewController: UIViewController, Injectable {
    
    typealias T = String
    privatevar textDependency: String!
    
    // here, the thing is text!
    func inject(text: String) {
        textDependency = text
    }
}
 
class MyIntDependencyViewController: UIViewController, Injectable {
    
    typealias T = Int
    privatevar numberDependency: Int!
    
    // here the thing is number!
    func inject(number: Int) {
        numberDependency = number
    }
}


Now, the implementation is super clear! The more I use associated types, the more I like them!




英文