Swift将数组附加到数组

时间:2018-05-23 09:14:49

标签: arrays json swift xcode

大家好我有这种数组的问题,所以基本上我想将数据传递给我的服务器,就像这样:

{adult=[["Mr", "Benedict Cumberbatch", "07", "September", "1989", "null", "0", "null", "null", "null", "null", "null"],["Mr", "Tony Stark", "17", "July", "1996", "null", "0", "null", "null", "null", "null", "null"]]}

我有这样的数组

["Mr", "Benedict Cumberbatch", "07", "September", "1989", "null", "0", "null", "null", "null", "null", "null"]

和这个

["Mr", "Tony Stark", "17", "July", "1996", "null", "0", "null", "null", "null", "null", "null"]

我用这段代码创建:

    PassengerModel.passenger_array_json.append(title)
    PassengerModel.passenger_array_json.append(name)
    PassengerModel.passenger_array_json.append(date!)
    PassengerModel.passenger_array_json.append(month!)
    PassengerModel.passenger_array_json.append(year!)
    PassengerModel.passenger_array_json.append("null")
    PassengerModel.passenger_array_json.append("0")
    PassengerModel.passenger_array_json.append("null")
    PassengerModel.passenger_array_json.append("null")
    PassengerModel.passenger_array_json.append("null")
    PassengerModel.passenger_array_json.append("null")
    PassengerModel.passenger_array_json.append("null")

所以我有一个想法,如果我将数组附加到数组将给我这个结果, 并试试这个:

PassengerModel.passenger_array_json_2.append(PassengerModel.passenger_array_json)

但它给了我一个错误,任何人都知道,不知怎的,我可以创建这样的数据:

["Mr", "Benedict Cumberbatch", "07", "September", "1989", "null", "0", "null", "null", "null", "null", "null"],["Mr", "Tony Stark", "17", "July", "1996", "null", "0", "null", "null", "null", "null", "null"]

1 个答案:

答案 0 :(得分:1)

你的代码究竟是什么?

let sherlock = ["Mr", "Benedict Cumberbatch"] //Implicit type of sherlock: [String] (or Array<String> if you want)
let ironman = ["Mr", "Tony Stark"]
var characters: [[String]] = [] //Here you create an array of arrays, so one entry for each superhero
characters.append(sherlock)
characters.append(ironman)

的工作原理。您无法将ironman附加到sherlock,因为sherlock是一个只包含字符串的数组,结果将是 ["Mr", "Benedict Cumberbatch", ["Mr", "Tony Stark"]](这不是你想要的,不再是一个字符串数组(第三个条目是一个数组......))。所以你需要为你的演员提供一个新阵列