我正在Xcode 8的iOS游乐场尝试这个,但它不起作用:
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
“...在自定义选项的实例中添加或删除成员 设置类型。“
文档引用remove()
函数,但这不起作用。我做错了什么?
答案 0 :(得分:3)
尝试更改all
的声明:
static let all: Direction = [.up, .left, .down, .right]
答案 1 :(得分: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 = []