- 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
推薦閱讀
- 數(shù)據(jù)之巔:數(shù)據(jù)的本質(zhì)與未來
- DB29forLinux,UNIX,Windows數(shù)據(jù)庫管理認(rèn)證指南
- 卷積神經(jīng)網(wǎng)絡(luò)的Python實(shí)現(xiàn)
- UDK iOS Game Development Beginner's Guide
- 數(shù)據(jù)庫應(yīng)用基礎(chǔ)教程(Visual FoxPro 9.0)
- iOS and OS X Network Programming Cookbook
- Sybase數(shù)據(jù)庫在UNIX、Windows上的實(shí)施和管理
- 基于OPAC日志的高校圖書館用戶信息需求與檢索行為研究
- 大數(shù)據(jù)技術(shù)入門
- 新基建:數(shù)據(jù)中心創(chuàng)新之路
- 數(shù)據(jù)庫原理與應(yīng)用
- 計(jì)算機(jī)視覺
- Deep Learning with R for Beginners
- 改進(jìn)的群智能算法及其應(yīng)用
- 數(shù)字化轉(zhuǎn)型實(shí)踐:構(gòu)建云原生大數(shù)據(jù)平臺(tái)