gpt4 book ai didi

swift - 枚举数组是 Swift 中的枚举?

转载 作者:搜寻专家 更新时间:2023-11-01 06:07:11 25 4
gpt4 key购买 nike

我正在关注 Apple's Swift/iOS tutorial它具有以下代码行:

button.setImage( filledStarImage, forState: [UIControlState.Highlighted, UIControlState.Selected] )

但是UIButton.setImage的签名定义是:

public func setImage(image: UIImage?, forState state: UIControlState)

没有接受 [UIControlState]() 数组的 setImage 重载。

显然有些巫术正在发生,谁能解释一下?

最佳答案

在 Swift 中,UIControlState 本身并不是一个枚举,而是一个结构。来自 UIControl 的语言引用:

Control State

The state of a control; a control can have more than one state at a time. States are recognized differently depending on the control. For example, a UIButton instance may be configured (using the setImage:forState: method) to display one image when it is in its normal state and a different image when it is highlighted.

Declaration

struct UIControlState : OptionSetType {
init(rawValue rawValue: UInt)
static var Normal: UIControlState { get }
static var Highlighted: UIControlState { get }
static var Disabled: UIControlState { get }
static var Selected: UIControlState { get }
static var Focused: UIControlState { get }
static var Application: UIControlState { get }
static var Reserved: UIControlState { get }
}

这里的关键是 OptionSetType 协议(protocol)(UIControlState 符合),它允许我们对静态结构属性进行“类似枚举”的访问,前提是它们有一个 RawValue,它是一个 BitwiseOperationsType。例如:

struct MyStruct : OptionSetType {
private var value: UInt
var rawValue: UInt { return self.value }
init(rawValue value: UInt) { self.value = value }

static var Normal: MyStruct { return self.init(rawValue: 1 << 0) }
static var Highlighted: MyStruct { return self.init(rawValue: 1 << 1) }
static var Disable: MyStruct { return self.init(rawValue: 1 << 2) }
// ...
}

let MyOptionsA : MyStruct = [MyStruct.Normal, MyStruct.Disable]
let MyOptionsB : MyStruct = [.Normal, .Disable]

MyOptionsB.contains(.Highlighted) // false
MyOptionsB.contains(.Normal) // true

查看符合 OptionsSetType 的实例方法(请参阅下面的语言引用链接)。除了成员(member)管理(例如 .contains(...) 如上所述;还有 .remove(...), .insert(..)), union(...)intersect(...) 等整洁集合操作也可用。

总结一下; UIButton.setImage 签名要求 forState state: UIControlState 是对的,但是,由于 OptionSetType 协议(protocol),数组外观 [UIControlState.Highlighted, UIControlState.Selected] 实际上是调用结构类型参数 UIControlState 的有效参数。

另请注意,根据我上面的示例,结构名称可以省略,因此将 [.Highlighted, .Selected] 作为 forState 参数发送只是一样好。


引用和好读物:

关于swift - 枚举数组是 Swift 中的枚举?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34502753/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com