與SWIFT 2有可能獲得相關的值使用反射(只讀)。
爲了簡化操作,只需將下面的代碼添加到項目中,並使用EVAssociated協議擴展您的枚舉。
public protocol EVAssociated {
}
public extension EVAssociated {
public var associated: (label:String, value: Any?) {
get {
let mirror = Mirror(reflecting: self)
if let associated = mirror.children.first {
return (associated.label!, associated.value)
}
print("WARNING: Enum option of \(self) does not have an associated value")
return ("\(self)", nil)
}
}
}
然後你就可以使用代碼訪問.asociated值是這樣的:
class EVReflectionTests: XCTestCase {
func testEnumAssociatedValues() {
let parameters:[EVAssociated] = [usersParameters.number(19),
usersParameters.authors_only(false)]
let y = WordPressRequestConvertible.MeLikes("XX", Dictionary(associated: parameters))
// Now just extract the label and associated values from this enum
let label = y.associated.label
let (token, param) = y.associated.value as! (String, [String:Any]?)
XCTAssertEqual("MeLikes", label, "The label of the enum should be MeLikes")
XCTAssertEqual("XX", token, "The token associated value of the enum should be XX")
XCTAssertEqual(19, param?["number"] as? Int, "The number param associated value of the enum should be 19")
XCTAssertEqual(false, param?["authors_only"] as? Bool, "The authors_only param associated value of the enum should be false")
print("\(label) = {token = \(token), params = \(param)")
}
}
// See http://github.com/evermeer/EVWordPressAPI for a full functional usage of associated values
enum WordPressRequestConvertible: EVAssociated {
case Users(String, Dictionary<String, Any>?)
case Suggest(String, Dictionary<String, Any>?)
case Me(String, Dictionary<String, Any>?)
case MeLikes(String, Dictionary<String, Any>?)
case Shortcodes(String, Dictionary<String, Any>?)
}
public enum usersParameters: EVAssociated {
case context(String)
case http_envelope(Bool)
case pretty(Bool)
case meta(String)
case fields(String)
case callback(String)
case number(Int)
case offset(Int)
case order(String)
case order_by(String)
case authors_only(Bool)
case type(String)
}
上面的代碼是從我的項目https://github.com/evermeer/EVReflection https://github.com/evermeer/EVReflection
我認爲你所做的是正確的(計算屬性,即)。枚舉可以有任何類型的關聯值,更重要的是任何數量。我沒有看到蘋果如何在不迫使我們陷入無數「as」和「if」的情況下提供速記訪問。 – courteouselk
順便說一句,如果您的枚舉具有與每種情況關聯的CGFloat,則可以考慮使用原始值而不是關聯。 – courteouselk
@AntonBronnikov原始值是常量,它們必須是唯一的,即不能有兩個具有不同值的「水平」實例。 – Arkku