在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)
}
}
}
然后,您可以使用以下代码访问关联的值:
class EVReflectionTests: XCTestCase {
func testEnumAssociatedValues() {
let parameters:[EVAssociated] = [usersParameters.number(19),
usersParameters.authors_only(false)]
let y = WordPressRequestConvertible.MeLikes("XX", Dictionary(associated: parameters))
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)")
}
}
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)
}
上述代码现在可以作为cocoapod susbspec使用,网址是
https://github.com/evermeer/Stuff#enum。此外,它还有一个枚举扩展,用于枚举所有枚举值。
case
语句中使用where
子句来删除几行代码:case .Text(let text) where text == nil:
。 - Mike Swhere
子句并让它继续执行。不过我还是会回到Any!
。将其变成枚举需要我编写过于冗长的代码。 - Matthew QuirosFormField
类中,value
已经是一个可选项。如果只有在有值时才设置FormField
的value
,那么您可以直接检查if field.value == nil
。这意味着您也不需要将枚举的关联值隐式解包为可选项。 - Mike SNilLiteralConvertible
。 - Matthew Quiros