zoukankan      html  css  js  c++  java
  • Swift学习笔记三

    协议和扩展

    在Objective-C中,协议是很常见也非常重要的一个特性,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.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关键字来标识该方法会改变结构体,而类声明中不需要给任何方法加此关键字,因为类的任何方法都可以改变类。

    用extension给现有的类型增加功能,比如新的方法或者计算过的属性等。

    也可以通过extension来给一个类型添加对某个协议的遵守,这个类型可以是在别的地方声明的,甚至是从第三方库或框架导入的。

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

    协议的名字可以像其他具名的类型名字一样被使用,比如创建一个包含很多对象的集合,这些对象都是不同的类型,但是它们都遵守同一个协议。当处理那些类型为某个协议的变量时,协议之外声明和定义的方法将无法调用。

    let protocolValue: ExampleProtocol = a
    println(protocolValue.simpleDescription)
    println(protocolValue.anotherProperty)  // Uncomment to see the error

    尽管protocolValue变量的运行时类型是SimpleClass,编译器仍然会将它看做显示指定的ExampleProtocol类型,这意味着你不能调用那些在SimpleClass中除了遵守ExampleProtocol协议之外定义的其他方法。

    泛型(Generics)

    用尖括号包含一个名字来创建一个泛型函数或者类型

    func repeat<Item>(item: Item, times: Int) -> [Item] {
        var result = [Item]()
        for i in 0..<times {
            result.append(item)
        }
        return result
    }
    repeat("knock", 4)

    可以创建泛型格式的函数、方法、类、枚举类型、结构体。

    enum OptionalValue<T> {
        case None
        case Some(T)
    }
    var possibleInteger: OptionalValue<Int> = .None
    possibleInteger = .Some(100)

    在类型名之后用where来指明一系列要求,比如要求某个数据类型来实现某个协议,要求两个类型必须相同,或者要求某个类必须拥有指定的基类

    func anyCommonElements <T, U where T: SequenceType, U: SequenceType, T.Generator.Element: Equatable, T.Generator.Element == U.Generator.Element> (lhs: T, rhs: U) -> Bool {
        for lhsItem in lhs {
            for rhsItem in rhs {
                if lhsItem == rhsItem {
                    return true
                }
            }
        }
        return false
    }
    anyCommonElements([1, 2, 3], [3]) //true

    简单的情况下,可以省略where而直接在冒号后面写协议或者类名,<T:Equatable>和<T where T:Equtable>是等价的。

  • 相关阅读:
    transaction sql
    谈谈tempdb在系统中的重要作用
    Windows快捷键
    sp_addlinkedserver使用方法
    大型网站用户登录信息保存实现的探讨
    Proj EULibHarn Paper Reading: Graspan: A SingleMachine DiskBased Graph System for Interprocedural Static Analyses of LargeScale Systems Code
    Proj EULibHarn Paper Reading: Towards Efficient LargeScale Interprocedural Program Static Analysis on Distributed DataParallel Computation
    Proj EULibHarn Paper Reading: APICraft: Fuzz Driver Generation for Closedsource SDK Libraries
    Proj EULibHarn Paper Reading: Systemizing Interprocedural Static Analysis of LargeScale Systems Code with Graspan
    Proj EULibHarn Paper Reading: Chianina: An Evolving Graph System for Flow and ContextSensitive Analyses of Million Lines of C Code
  • 原文地址:https://www.cnblogs.com/dson/p/4552090.html
Copyright © 2011-2022 走看看