我对PushRow有一点问题。 我通过JSON检索我的值,但我不能将它们放在PushRow中:/
我的价值观:
picturebox
1 /声明一个结构来保存id和值:
{
"listValue": [{
"id": 1,
"value": "Value 1"
},{
"id": 2,
"value": "Value 2"
},{
"id": 3,
"value": "Value 3"
}]
}
2 /使其符合Equatable
struct MyStruct {
var id: Int
var value: String
init(id: Int, value: String) {
self.id = id
self.value = value
}
}
3 / Make MyStruct符合CustomStringConvertible
struct MyStruct {
var id: Int
var value: String
init(id: Int, value: String) {
self.id = id
self.value = value
}
}
extension MyStruct: Equatable {}
func ==(lhs: MyStruct, rhs: MyStruct) -> Bool {
let areEqual = lhs.id == rhs.id &&
lhs.value == rhs.value
return areEqual
}
现在,我有一个问题是将json listValue响应转换为MyStruct数组..(不能指定类型'[String:JSON]'的值来键入'[MyStruct]') 怎么做?
在我的代码中,我使用Eureka
struct MyStruct : CustomStringConvertible {
var id: Int
var value: String
init(id: Int, value: String) {
self.id = id
self.value = value
}
var description: String {
return "\(self.id)"+" "+"\(self.value)"
}
}
extension MyStruct: Equatable {}
func ==(lhs: MyStruct, rhs: MyStruct) -> Bool {
let areEqual = lhs.id == rhs.id &&
lhs.value == rhs.value
return areEqual
}
我的listValue是一个JSON(带有SwiftyJSON)
你有想法帮助我吗?
答案 0 :(得分:0)
解决方案#1(带结构):
struct MyStruct : CustomStringConvertible {
var id: Int
var value: String
init(id: Int, value: String) {
self.id = id
self.value = value
}
var description: String {
//return "\(self.id)"+" "+"\(self.value)"
return "\(self.value)"
}
}
extension MyStruct: Equatable {}
func ==(lhs: MyStruct, rhs: MyStruct) -> Bool {
let areEqual = lhs.id == rhs.id &&
lhs.value == rhs.value
return areEqual
}
和
var arrayOfMyStruct:[MyStruct] = []
for item in item["listValue"].arrayValue {
print(item["id"].intValue)
print(item["value"].stringValue)
print("#############")
arrayOfMyStruct.append(MyStruct(id: item["id"].intValue, value: item["value"].stringValue))
}
form.last! // recupère la dernière section
<<< PushRow<MyStruct>(idItem) {
$0.title = item["libItem"].stringValue
$0.options = arrayOfMyStruct
}
它有效!
解决方案#2(带阵列):
var Liste : [String] = []
for (idvaleur,TabValeur):(String, JSON) in item["listValue"] {
print(TabValeur["id"])
print(TabValeur["value"])
print("#######")
Liste.append(TabValeur["value"].stringValue)
}
print(Liste)
form.last! // recupère la dernière section
<<< PushRow<String>(idItem) {
$0.title = item["libItem"].stringValue
$0.options = Liste
}
答案 1 :(得分:0)
现在,如果你想检索选择的id(而不是显示的内容......即:value)
let valeursFormulaire = self.form.values(includeHidden: true)
for (idvaleur,valeur):(String, Any?) in valeursFormulaire {
if let laValeur = valeur {
let typeDeChamps = String(laValeur.dynamicType)
switch(typeDeChamps){
case "MyStruct":
if let rowValue = self.form.rowByTag(idvaleur)?.baseValue as? MyStruct {
print("\(rowValue.id)") // id here :)
}
default:
print("\(idvaleur)"+" "+"\(laValeur)")
}
}
}