神刀安全网

Swift: Making the Associated Type Parameter Readable in Protocols

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 .

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:

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:

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!

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!

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!

转载本站任何文章请注明:转载至神刀安全网,谢谢神刀安全网 » Swift: Making the Associated Type Parameter Readable in Protocols

分享到:更多 ()

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
分享按钮