官术网_书友最值得收藏!

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
主站蜘蛛池模板: 章丘市| 富顺县| 文登市| 通化县| 刚察县| 诏安县| 崇信县| 呼伦贝尔市| 江达县| 阿拉善左旗| 彩票| 吕梁市| 赣州市| 那坡县| 林芝县| 西乡县| 苗栗县| 赤城县| 东宁县| 高邑县| 胶南市| 柘荣县| 尉氏县| 宜春市| 清流县| 泗洪县| 房产| 泽库县| 上饶县| 昌吉市| 鄯善县| 明星| 府谷县| 儋州市| 怀集县| 体育| 广宁县| 阿巴嘎旗| 永胜县| 汤原县| 安乡县|