I need to get the name of enum associated value.
for example:
enum App{
case iOS(version:String)
case android(version:String, build:Int)
}
let iosApp = App.iOS(version:"2.30.11")
let androidApp = App.android(version:"2.30.11",build:101)
let iosMirror = Mirror(reflecting: iosApp)
for case let (key?, value) in iosMirror.children {
print("\(key)-\(value)") //this will print:iOS-2.30.11,missing the value name-"version",the string "version" was I need.
}
let androidMirror = Mirror(reflecting: androidApp)
for case let (key?, value) in androidMirror.children {
print("\(key)-\(value)") //this will print:android-(version:"2.30.11",build:101)
}
question: I want get the associated value name "version" of iosApp from iosMirror,How should i do? or using other way(not Mirror) to get strings "version".
Not sure if this is what you are after but you could let your enum implement CustomStringConvertible
to get a specific output.
enum App : CustomStringConvertible {
var description: String { get {
switch self {
case .iOS(version: let v):
return "version: \(v)"
case .android(version: let v, build: let b):
return "version: \(v) build: \(b)"
}
}
}
case iOS(version: String)
case android(version:String, build:Int)
}
let iosApp = App.iOS(version:"2.30.11")
let androidApp = App.android(version:"2.30.11",build:101)
print(iosApp)
print(androidApp)
iOS-(version: "2.30.11") android-(version: "2.30.11", build: 101)gets printed with Xcode10(Swift4.2) so it is a bug from an older version.
-@Purpose
I tested this code in Xcode 10-beta 6,it print iOS-(version: "2.30.11"). this question solved.
thanks @Purpose.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.