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

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
主站蜘蛛池模板: 和政县| 大渡口区| 辉南县| 威远县| 连城县| 南京市| 邢台县| 岚皋县| 南城县| 图木舒克市| 江北区| 仪征市| 安龙县| 大港区| 平邑县| 余庆县| 晋州市| 池州市| 新绛县| 云霄县| 平乐县| 清水河县| 乡城县| 兴海县| 女性| 平湖市| 桃江县| 马龙县| 库车县| 红桥区| 仁布县| 永顺县| 宾阳县| 来凤县| 新化县| 陆川县| 启东市| 土默特右旗| 德惠市| 晋州市| 桂阳县|