在Swift中,使用Codable struct和CodingKeys emum, 如果我有一个Coordinate对象,如何获取纬度和经度CodingKeys值,作为数组[“ 1”,“ 2”]
struct Coordinate: Codable {
var latitude: Bool?
var longitude: Bool?
var elevation: Bool?
enum CodingKeys: String, CodingKey {
case latitude = "1"
case longitude = "2"
case elevation = "3"
}
}
以及如何只为true的变量获取所有CodingKeys值? 例如,如果经度和海拔高度设置为true,我将获得数组[“ 2,” 3“]
答案 0 :(得分:0)
CaseIterable
会有所帮助
struct Coordinate: Codable {
var latitude: Bool?
var longitude: Bool?
var elevation: Bool?
enum CodingKeys: String, CodingKey, CaseIterable {
case latitude = "1"
case longitude = "2"
case elevation = "3"
}
var allKeys: [String] {
CodingKeys.allCases.map { $0.stringValue }
}
}
答案 1 :(得分:-1)
如果我正确理解,可能会发生以下情况:
let myCoordinates = Coordinate(latitude: true, longitude: false, elevation: true)
var myArray: [String] = []
if myCoordinates.latitude ?? false {
myArray.append("1")
}
if myCoordinates.longitude ?? false {
myArray.append("2")
}
if myCoordinates.elevation ?? false {
myArray.append("3")
}
另外,谢谢!我不知道Codable存在,现在我想我可以在项目中使用它了!