2016-09-10 25 views
2

我想這在iOS的操場刪除成員在Xcode中8,但它不工作:如何從OptionSet

struct Direction: OptionSet { 
    let rawValue: UInt8 
    static let none = Direction(rawValue: 0) 
    static let up = Direction(rawValue: 1 << 0) 
    static let left = Direction(rawValue: 1 << 1) 
    static let down = Direction(rawValue: 1 << 2) 
    static let right = Direction(rawValue: 1 << 3) 
    static let all = [up, left, down, right] 
} 

var directions = Direction.all 
directions.remove(.up) // Error: Missing argument label 'at:' in call 

Apple's documentation表明,我應該能夠

」。 ..從自定義選項 設置類型的實例中添加或刪除成員。「

該文檔涉及remove()函數,但這不起作用。我究竟做錯了什麼?

回答

2

嘗試改變的all的聲明:

static let all: Direction = [.up, .left, .down, .right] 
1

的問題是,沒有上下文,SWIFT將推斷字面陣列是[Element]類型(又名Array<Element>)的。因此沒有明確的類型註釋,

static let all = [up, left, down, right] 

會被推斷爲一個[Direction],而不是一個Direction(這就是爲什麼編譯器會提示您使用的方法remove(at:))。

因此,解決方案,因爲@OOPer has already said,是簡單地給all一個明確的類型註釋:

static let all : Direction = [up, left, down, right] 

將利用OptionSet的(而不是Array的)符合ExpressibleByArrayLiteral


作爲邊注,顯式none選項是多餘的,因爲這可以由空集來表示:

let none : Direction = []