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

Swift开发第十二篇——protocol组合&static和class

2016-03-26 07:42 429 查看
本篇分为两部分:


一、Swift 中 protocol 组合的使用

二、Swfit 中 static和class 的使用


  

一、Swift 中 protocol 组合的使用

  在 Swift 中我们可以使用 Any 来表示任意类型(public typealias Any = protocol<>),是一个 protocol<>的同名类型,需要实现空接口的接口,其实就是任意类型的意思。

protocol<ProtocolA, ProtocolB, ProtocolC> 等价于
protocol ProtocolD: ProtocolA, ProtocolB, ProtocolC {
//...
}


protocol 组合可以用 typealias 来命名的,于是上面的 ProtocolD 协议可以替换为

typealias ProtocolAll = protocol<ProtocolA, ProtocolB, ProtocolC>


如果某些接口我们只用一次的话,可以直接匿名化

struct ProtocolStruct {
static func test1(pro: protocol<ProtocolA, ProtocolB>) {
//...
}
static func test2(pro: protocol<ProtocolB, ProtocolC>) {
//...
}
}


如果实现多个接口时接口内的方法冲突的话只要在调用前进行类型转换就可以了

protocol A {
func wang() -> Int
}
protocol B {
func wang() -> String
}
class AnClass: A, B {
func wang() -> Int {
return 0
}
func wang() -> String {
return "强转"
}
}
let instance = AnClass()
let num = (instance as A).wang()
let str = (instance as B).wang()


二、Swfit 中 static和class 的使用

在 Swift1.2及以后,我们可以在 class 中使用 static 来声明一个类作用域的变量:

class MyClass {
static var bar: AnClass?
}


这种写法是合法的,有了这个特性之后,像单例的写法就很简单了

protocol MyProtocol {
static func foo() -> String
}
struct MyStruct: MyProtocol {
static func foo() -> String {
return "MyStruct"
}
}
enum MyEnum: MyProtocol {
static func foo() -> String {
return "MyEnum"
}
}
class TestClass: MyProtocol {
// 在 class 中可以使用 class
class func foo() -> String {
return "TestClass.foo()"
}
// 也可以使用 static
static func bar() -> String {
return "AnClass.bar()"
}
}


protocl 是比较特殊的,在 Swift 中 class, struct 和 enum 都是可以实现某个 protocol 的,这时候我们就会不知道在什么情况下使用 static,什么情况下使用 class。在 Swift2.0 之后,只要记住在任何时候使用 static 都是没有问题的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: