我是Swift中的新手,我希望将我的结构转换为参数,以便用Alamofire 4发布它。 请原谅我的英语不好。
我的结构在另一个类中:
import Foundation
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
}
}
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))
}
}
现在在Main Class中我想发布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
访问struct(structUser)中的变量 谢谢你的帮助!请解释完整的解决方案,因为我想了解它是如何工作的。 THX!答案 0 :(得分: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()