Swift學習5---協議(protocol)和擴充(extension)

來源:互聯網
上載者:User

標籤:

1.協議

  Swift使用protocol定義協議:

protocol ExampleProtocol {    var simpleDescription: String { get }    mutating func adjust()}

  類型、枚舉和結構都可以實現協議:

class SimpleClass: ExampleProtocol {    var simpleDescription: String = "A very simple class."    var anotherProperty: Int = 69105    func adjust() {        simpleDescription += " Now 100% adjusted."    }}var a = SimpleClass()a.adjust()let aDescription = a.simpleDescriptionstruct SimpleStructure: ExampleProtocol {    var simpleDescription: String = "A simple structure"    mutating func adjust() {        simpleDescription += " (adjusted)"    }}var b = SimpleStructure()b.adjust()let bDescription = b.simpleDescription

2.擴充

  擴充用於在已有的類型上增加新的功能(比如新的方法或屬性),Swift使用extension聲明擴充:

extension Int: ExampleProtocol {    var simpleDescription: String {        return "The number \(self)"    }    mutating func adjust() {        self += 42    }}7.simpleDescription

 

Swift學習5---協議(protocol)和擴充(extension)

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.