- Swift Functional Programming(Second Edition)
- Dr. Fatih Nayebi
- 170字
- 2021-07-02 23:54:29
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
推薦閱讀
- PyTorch深度學(xué)習(xí)實戰(zhàn):從新手小白到數(shù)據(jù)科學(xué)家
- SQL Server 2016 數(shù)據(jù)庫教程(第4版)
- 數(shù)據(jù)庫基礎(chǔ)與應(yīng)用:Access 2010
- 從0到1:數(shù)據(jù)分析師養(yǎng)成寶典
- 城市計算
- 數(shù)據(jù)科學(xué)工程實踐:用戶行為分析與建模、A/B實驗、SQLFlow
- HikariCP連接池實戰(zhàn)
- TextMate How-to
- 貫通SQL Server 2008數(shù)據(jù)庫系統(tǒng)開發(fā)
- 數(shù)據(jù)庫原理與設(shè)計實驗教程(MySQL版)
- 算法設(shè)計與分析
- 中國云存儲發(fā)展報告
- Hands-On Deep Learning for Games
- 大數(shù)據(jù)測試技術(shù):數(shù)據(jù)采集、分析與測試實踐(在線實驗+在線自測)
- 數(shù)字化轉(zhuǎn)型實踐:構(gòu)建云原生大數(shù)據(jù)平臺