简体   繁体   中英

Array of strings and ints in swift

I am trying to make an array of arrays where each nested array has a string and an integer.

I have seen you can use structs but all I want to do is make them a constant, and I want to know if there is a way to do it without having to type loads of extra stuff

let items: [[String, Int]] = [["A", 1], ["B", 2], ["C", 3]]

I think what you want is an array of tuples, not an array of arrays. That implementation would look like this:

let items: [(String, Int)] = [("A", 1), ("B", 2), ("C", 3)]

You could access these properties like this:

let itemOneString = items[0].0 // "A"
let itemOneInt = items[0].1 // 1

它会为你工作:

let items: [[(String, Int)]] = [[("A", 1)], [("B", 2)], [("C", 3)]]

  1. Array is collection of similar data types. It can not contain heterogeneous types data.

But if you still want to do it. There are other workarounds like create array of dictionary like this.

let items: [[String: Any]] = [["String" : "A", "Int" : 1], ["String" : "B", "Int" : 2]]

or create an array of Tuples .

let items: [(String, Int)] = [("A", 1), ("B", 2), ("C", 3)]

You can add any number of items in Tuple or Dictionary .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM