Protocol Flashcards
What is a protocol and why use it?
A blueprint of methods, properties, and other requirements that suit a particular task or piece of functionality.
It’s a great way to make code sexier by having something that would have been used multiple times in various places, be accessible from one area.
Protocols can also serve as types.
What is a gettable property?
A property you can read but not set it after we’ve given it an initial value
How you do you get a computed property?
You get a computed property value by doing some computation
It had no storage
TF: Protocols can require that conforming types have specific instance properties, instance methods and type methods.
True
If a stored property requirement in a protocol is declared as gettable and settable, the property cannot be implemented as a:
Constant, because they are not settable
What is a protocol?
A contract of methods, properties, and other requirements
How can protocols serve as types?
As a parameter type or return type in a function, method or initializer
As the type of a constant, variable, or property
As the type of items in an array, dictionary, or other containers
TF: Protocols are types just like classes and structs?
True
TF: == is a protocol?
True
TF: Protocols describe what should be implemented but does not require a specific implementation.
True
When trying to decide whether or not to use a protocol, how can you implement is-a and has-a relationships?
Class Airplane and Class Jetplane are is-a because a jet plane is a type of airplane. → when we have a is-a relationship, Inheritance is best for design pattern
Class Airplane and struct Bird are a has-a because they are not really related, but they both can fly. → when we have a has-a relationship, we should use a fly protocol in this case.
Protocols typically end with what suffix?
Able
But this isn’t always true
For protocols, how do you set up a property?
Either var or let name Type And whether it is gettable or gettable and settable I.e → var firstName: String { get set }
What are type methods?
Methods that are defined on the type itself rather than an instance Need to use static before the name of method to use it in class or struct In example below, the method is defined in the func itself, not before.
struct User: PrettyPrintable, Equatable {
let name: String
let age: Int
let address: String
static func ==(lhs: User, rhs: User) -> Bool { return lhs.name == rhs.name && lhs.age == rhs.age && lhs.address == rhs.address } }
What does AnyObject vs Any represent?
AnyObject - An instance of any class type Any - can represent anything including functions