除了用int设置可检查的枚举外,还可以使用字符串设置它们。尽管不如下拉菜单那么可取,但至少此选项提供了一定程度的可读性。
仅Swift选项:
enum Shape: String {
case Rectangle = "rectangle"
case Triangle = "triangle"
case Circle = "circle"
}
var shape = Shape.Rectangle
@available(*, unavailable, message: "This property is reserved for Interface Builder. Use 'shape' instead.")
@IBInspectable var shapeName: String? {
willSet {
if let newShape = Shape(rawValue: newValue?.lowercased() ?? "") {
shape = newShape
}
}
}
这是可能的也是得到这个用Objective-C的工作,以及通过增加一个初始化的枚举。但是,编译器仅会在swift代码中显示仅IB属性的“不可用”错误。
具有Obj-C兼容性的Swift选件:
@objc enum Shape: Int {
case None
case Rectangle
case Triangle
case Circle
init(named shapeName: String) {
switch shapeName.lowercased() {
case "rectangle": self = .Rectangle
case "triangle": self = .Triangle
case "circle": self = .Circle
default: self = .None
}
}
}
var shape = Shape.Rectangle
@available(*, unavailable, message: "This property is reserved for Interface Builder. Use 'shape' instead.")
@IBInspectable var shapeName: String? {
willSet {
if let newShape = Shape(rawValue: newValue?.lowercased() ?? "") {
shape = newShape
}
}
}