- Swift Functional Programming(Second Edition)
- Dr. Fatih Nayebi
- 170字
- 2021-07-02 23:54:30
Protocols as types
Any protocol that we define will become a fully-fledged type to use in our code. We can use a protocol as follows:
- A parameter type or return type in a function, method, or initializer
- The type of a constant, variable, or property
- The type of items in an array, dictionary, or another container
Let's look at the following example:
protocol ExampleProtocol {
var simpleDescription: String { get }
mutating func adjust()
}
// Classes, enumerations and structs can all adopt protocols.
class SimpleClass: ExampleProtocol {
var simpleDescription: String = "A very simple class example"
var anotherProperty: Int = 79799
func adjust() {
simpleDescription += "Now 100% adjusted..."
}
}
var aSimpleClass = SimpleClass()
aSimpleClass.adjust()
let aDescription = aSimpleClass.simpleDescription
struct SimpleStructure: ExampleProtocol {
var simpleDescription: String = "A simple struct"
// Mutating to mark a method that modifies the structure - For
classes we do not need to use mutating keyword
mutating func adjust() {
simpleDescription += "(adjusted)"
}
}
var aSimpleStruct = SimpleStructure()
aSimpleStruct.adjust()
let aSimpleStructDescription = aSimpleStruct.simpleDescription