2017-06-22 84 views
0

Iam新的Swift中,我想將我的結構轉換爲參數與Alamofire 4發佈它。 請原諒我的英語不好。Swift 3結構參數Alamofire4

我的結構是在另一大類:

import Foundation 

類structUser:NSObject的{

var myStructUser = [person]() 


struct person { 
    var firstName : String 
    var lastName : String 
    var age: Int 
    init (firstName : String, lastName : String, age : Int) { 
     self.firstName = firstName 
     self.lastName = lastName 
     self.age = age 

    } 
} 

override init(){ 
    myStructUser.append(person(firstName: "John", lastName: "Doe", age: 11)) 
    myStructUser.append(person(firstName: "Richard", lastName: "Brauer", age : 22)) 
    myStructUser.append(person(firstName: "Merrideth", lastName: "Lind", age : 55)) 
} 

}

現在

在主類我要發佈Alamofire,卻怎麼也我只轉換結構的名字和年齡?

import UIKit 

類的ViewController:UIViewController的{

let classStructUser = structUser() 

override func viewDidLoad() { 
    super.viewDidLoad() 
    // Do any additional setup after loading the view, typically from a nib. 
    print(classStructUser.myStructUser) 
} 


func postJson(){ 
    //need format [String : Any] 
    for item in classStructUser.myStructUser{ 
     // var name = classStructUser.myStructUser.name 
     // var age = classStructUser.myStructUser.age 

    } 

    print(classStructUser.myStructUser) 

    /*here i need the Json in format: 

    { 
    "name":"John", 
    "age":11 
    } 

    { 
    "name":"Richard", 
    "age":22 
    } 

    { 
    "name":"Merrideth", 
    "age":55 
    } 


    an so on array.count 
    */ 
} 

}

另一個問題:

如何從VieControllerClass

訪問變量的結構(structUser)

THX您的幫助!並請解釋完整的解決方案,因爲我想了解它是如何工作的。 Thx!

回答

0
class structUser: NSObject{ 

    var myStructUser = [person]() 

    struct person { 
     var firstName : String 
     var lastName : String 
     var age: Int 
     init (firstName : String, lastName : String, age : Int) { 
      self.firstName = firstName 
      self.lastName = lastName 
      self.age = age 

     } 

     static func jsonArray(array : [person]) -> String 
     { 
      return "[" + array.map {$0.jsonRepresentation}.joined(separator: ",") + "]" 
     } 

     var jsonRepresentation : String { 
      return "{\"name\":\"\(firstName)\",\"age\":\"\(age)\"}" 
     } 
    } 

    func jsonRepresentation() -> String { 
     return person.jsonArray(array: myStructUser) 
    } 

    override init(){ 
     myStructUser.append(person(firstName: "John", lastName: "Doe", age: 11)) 
     myStructUser.append(person(firstName: "Richard", lastName: "Brauer", age : 22)) 
     myStructUser.append(person(firstName: "Merrideth", lastName: "Lind", age : 55)) 
    } 
} 

並且像這樣使用它。

let jsonString = classStructUser.myStructUser.jsonRepresentation() 
+0

這就是全部?我怎樣才能選擇姓名和年齡? – silazzz

+0

好的,謝謝!我會測試它!你能回答我的第二個問題嗎? – silazzz

+0

查看更新的答案 – Bilal