In WWDC15 Apple suggested to always start with Protocol.
like SubClasses, Structs inherit data from Protocol. All the methods in Protocol must exist on Struct. And you cannot change data type of them. ()
Protocols are rules or minimum requirements (functions and variables) that classes and structs need to have (). We can add whatever we want.
let cannot be used in Protocols. Only var can be used.
Sample Codes
Example 1
protocol Vehicle {
// Properties
var name: String { get } // car, bike, etc.
var currentPassengers: Int { get set } // number passengers in default
// Methods
func estimateTime(for distance: Int) -> Int
func travel(distance: Int)
}
Technical Protocol Inheritance
Even if you not write the name of the protocol, swift understands and runs the protocol in background.
protocol Person {
var name: String { get }
func sayHello()
}
extension Person {
func sayHello() {
print("Hi, I'm \(name)")
}
}
struct Employee: Person {
let name: String
}
let taylor = Employee(name: "Taylor Swift")
taylor.sayHello()
// print: Hi I'm Taylor Swift
Protocols cannot have boddies, bodies can only be in extensions
protocol Building {
var type: String { get }
var rooms: Int { get }
var cost: Int { get set }
var agent: String { get set }
// func printSummary()
func printSummary() { // Error: Protocol methods must not have bodies
print("Talk to \(agent) to buy this \(type) for $\(cost).")
}
}
//extension Building {
// func printSummary() {
// print("Talk to \(agent) to buy this \(type) for $\(cost).")
// }
//}