SwiftOptional Swift编程珠玑iOS学习开发

[Swift2.0~3.0系列]OptionSetType使用(

2015-09-20  本文已影响2173人  NinthDay

1.Option set介绍

swift1.2 设置Option set只需要遵循RawOptionsetType协议即可。早前是这么声明选项集的:

struct Inventory:RawOptionSetType {
    var rawValue:UInt = 0
    init(rawValue:UInt){self.rawValue = rawValue}
    init(nilLiteral:()){rawValue = 0}
    func toRaw()->UInt{return rawValue}
    var boolValue:Bool{return rawValue != 0}
    
    static func fromRaw(raw:UInt)->Inventory?{return self(rawValue: raw)}
    static func fromMask(raw:UInt)->Inventory{return self(rawValue: raw)}
    static var allItems:Inventory{return self(rawValue: 0)}
    static func convertFromNilLiteral()->Inventory{self(nilLiteral: ())}
    static var allZeros:Inventory{return self(rawValue: 0)}
    
    
    static var Sword:Inventory{return self(rawValue: 1<<1)}
    static var Helmet:Inventory{return self(rawValue: 1<<2)}
    static var Shield:Inventory{return self(rawValue: 1<<3)}
}

var inventory:Inventory = .Sword | .Shield
if inventory & .Shield != nil{
    println("has shield")
}

卧槽这不是就是或运算吗,确实,经常在设置options时用得比较频繁,而现在的RawOptionsetType协议已经不复存在,取而代之的是OptionSetType,因此可能语法声明和使用上稍有不同,重拾难度。上文代码使用swift2.0改写后是这样的:

struct Inventory:OptionSetType {
    let rawValue:Int
    
    static let Sword = Inventory(rawValue: 1)
    static let Helmet = Inventory(rawValue: 1<<1)
    static let Shield = Inventory(rawValue: 1<<2)
}

var inventory:Inventory = [.Sword,.Shield]
if inventory.contains(inventory){
    print("has shield")
}

代码清爽,且提供了许多优秀的方法,比如contains,remove等对集合的操作。

2.实战运用

2.1设置可视化约束时代码改写

swift1.2前,我们经常习惯将options设为nil,但swift2.0中开始报错,修改方法如下

//swift1.2语法
let c1 = NSLayoutConstraint.constraintsWithVisualFormat("H:|-(20)-[v(100)]",
    options: nil, metrics: nil, views: ["v":v1]) as [NSLayoutConstraint]
//swift2.0语法
let c1 = NSLayoutConstraint.constraintsWithVisualFormat("H:|-(20)-[v(100)]",
    options: [], metrics: nil, views: ["v":v1]) as [NSLayoutConstraint]

2.2设置视图的autoresizingMask

swift1.2前,我们习惯使用|来对两个选项进行或运算,如下

v1.autoresizingMask = .FlexibleTopMargin | .FlexibleLeftMargin

而swift2.0使用optionSetType之后,声明方式是使用[]中添加的方式。

v1.autoresizingMask = [.FlexibleTopMargin,.FlexibleLeftMargin]

3 swift3.0中的用法

请见swiftgg Swift 中的选项集合 一文

上一篇下一篇

猜你喜欢

热点阅读