您的位置:首页 > 移动开发 > Swift

Swift学习笔记三

2015-06-04 15:59 573 查看
协议和扩展

在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>是等价的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: