Protocols in Swift - Part 1
So I got something wrong - the next course in my 'Beginner IOS' track is Protocols, not making an app! Not sure how that happened. Anyway, I'm not sure what Protocols are, but I assume it's do with more complex methods. Here we go....
What is a Protocol?
Pasan uses the coffee shop example. The concept is to define a blueprint of methods, properties and other behaviours. Expected behaviours.
An error comes up here as I have not put in the necessary properties.
What is a Protocol?
Pasan uses the coffee shop example. The concept is to define a blueprint of methods, properties and other behaviours. Expected behaviours.
protocol FullNameable {
var fullName: String { get }
}
So that's the syntax for protocols. Whatever uses this protocol must use the fullName property and apparently it is 'gettable'. Not sure what that means...yet.... OK, we can read the property but not set it until we get an initial value....still not clear!
Creating a Protocol
struct User: FullNameable {
}
struct User: FullNameable {
var fullName: String
}
let user = User(fullName: "Clint Lint")
Ok, so the properties if using a protocol as part of a struct/class (like the subclass) must use the same properties, with the same type. At the moment, it's not clear what the advantage of using protocol is, as I could have done the same with the struct.
A protocol should provide an IMPLEMENTATION....
struct Friend: FullNameable {
let firstName: String
let middleName: String
let lastName: String
var fullName: String {
return "\(firstName) \(middleName) \(lastName)"
}
}
let friend = Friend(firstName: "Clint", middleName: "Flint", lastName: "Lint")
friend.fullName
So with this example, we have put in three stored properties, then put in a computed property - fullName - this is the one that is shared with the protocol. It's 'computed' because something has been done with it - in this case String Interpolation. OK so a protocol shows you what should be implemented but how you do it - it's up to the class, structure or enumeration for that! Starting to make more sense now....
OK, that will do for now. It's starting to click after doing the challenges. At first it seemed pointless to have a protocol, when the same can be done in structs/classes/enums. However, the point seems to be to be that you can create some sort of blueprint, which then structs/classes/enums use in terms of which properties can be accessed, with how you get there not being a problem, as long as the same variable is used.
Still not quite making full sense! But it's coming! Will go through the next bit of the Treehouse next time, then look up some additional reading if it's not too clear.
Comments
Post a Comment