zoukankan      html  css  js  c++  java
  • iOS-swift-协议和拓展

    1 协议(protocol

        使用关键字 protocol 创建协议。

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

        类、枚举和结构体都支持协议。

    lass 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.simpleDescription
     
    struct SimpleStructure: ExampleProtocol {
        var simpleDescription: String = "A simple structure"
        mutating func adjust() {
            simpleDescription += " (adjusted)"
        }
    }
    var b = SimpleStructure()
    b.adjust()
    let bDescription = b.simpleDescription

          注意关键字 mutating,在结构体 SimpleStructure 中使用 mutating 实现协议中的方法。而在类中 SimpleClass,却不需要关键字 mutating 实现协议方法,因为类中方法本身就不需要关键字mutating 声明。

    2 拓展(extension

        使用关键字 extension 创建一个已存在类型的拓展。

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

    恩,努力。

  • 相关阅读:
    易用性问题回复
    阅读心得2:《余额宝技术架构及演进 》
    假期周进度报告8
    假期周进步报告7
    假期周进度报告6
    假期周进度报告5
    假期周进度报告4
    假期周进度报告3
    JAVA中SSH框架
    一张图说明CDN网络的原理
  • 原文地址:https://www.cnblogs.com/mengdongsky/p/7044808.html
Copyright © 2011-2022 走看看