This workshop will be retired on May 31, 2020.
Associated Type Constraints2:35 with Pasan Premaratne
Swift 4 allows for the addition of constraints to associated types using a where clause. While this seems like a small change it allows for much more expressive types.
Swift Evolution Proposals
In addition to composing classes and protocols, 0:00 Swift 4 adds another change that allows for a much more expressive type system. 0:03 SEO 142, the proposal, 0:08 allows us to constrain associated types in a protocol using a where clause. 0:10 In Swift 3, where clauses could only be used in generics. 0:15 By moving this to the protocol level, 0:19 many of the implementations of existing types have been cleaned up. 0:21 Here is an example of what the interface for sequence looked like in Swift 3. 0:26 I'm only focusing on the associated types here. 0:30 This is what it looks like in Swift 4. 0:35 So that although it's a small change, you'll see that where in Swift 3, 0:37 we only have the iterator. 0:41 In Swift 4, the type defines both an iterator and an element. 0:44 In Swift 3, the associated type element was defined in the iterator protocol type. 0:49 This meant that if we wanted to define element in sequence as well, 0:55 we would have to add a constraint to make sure the associated types match up every 0:58 time we extended sequence. 1:02 So for example, if I wanted to do something like this, 1:03 extension sequence where, now if this was in Swift 3. 1:07 I would have to write, Self.Element is an Int, 1:11 Self.Element = self.Iterator.Element. 1:17 So this is something we'd have to do in Swift 3, 1:22 because we would have to make sure that element and iterator.element are the same. 1:24 Now by adding the ability to define where constraints on the associated type itself, 1:29 we can clean up code like this. 1:34 Because Sequence. 1:36 So if I command click, and jump to the definition. 1:37 Because Sequence already constrains it, it says, we have an associatedtype element. 1:43 And we're ensuring, we're adding a constraint here, 1:48 that says Self.Element == Self.Iterator.Element. 1:51 By being able to move this to the protocol level and 1:54 add a where clause to the associated type, we can clean up code like this and 1:56 get rid of this element = Iterator.Element every time we need to extend it. 2:01 And can simply focus on the constraints we want to add. 2:06 In addition to cleaning things up nicely, 2:09 it means that implementation details can be hidden again. 2:12 So as a user here, 2:15 I don't have to understand that interor protocol is a part of Sequence. 2:16 I don't need to know what it does. 2:21 I can just constrain the associated types that are part of Sequence itself and 2:22 not have to go to the underlying protocols. 2:26 So a simple change, but now the type system is a lot more flexible. 2:29 It makes our code cleaner. 2:34
You need to sign up for Treehouse in order to download course files.Sign up