1

You can create a two dimensional array of one type of variable in swift with:

var array2D: [[String]] = [["hi", "bye"], ["hello", "goodbye"]]

I want to create a two dimensional array with the second variable a Float along the following lines:

var array2d2types = [[String,Float]] = [["height",1],["width",2]]

But this gives error: Cannot assign to immutable expression of type '[[Any]]'

How can I create an array of arrays each of which has a String and a Float?

4
  • 1
    Use a tuple (or a custom struct) instead. Commented Jul 25, 2019 at 16:33
  • Leo, I tried to downcast from Any to Float and ran into problems. Commented Jul 25, 2019 at 16:38
  • 1
    Don't do that I would suggest you using an array of CGSize objects let sizes: [CGSize] = [.init(width: 2, height: 1)] Commented Jul 25, 2019 at 16:39
  • Using width and height may have been misleading These could be any string and why not to think of them generically what you will do with key names in your app flow ???? Commented Jul 25, 2019 at 16:44

2 Answers 2

5

Swift arrays are homogeneous, so you cannot store different typed elements in the same array. However, you can achieve your goals using an array of tuples instead of nested arrays.

let array: [(String,Float)] = [("height",1),("width",2)]

You can access the tuples using the normal subscript syntax

let firstTuple = array[0]

and the elements of the tuple using dot syntax

let height = firstTuple.0
let heightValue = firstTuple.1

However, you should use a custom struct or even better the built-in CGSize for storing height-width values.

Sign up to request clarification or add additional context in comments.

3 Comments

How would I access these? Would I access one tuple using array[0]? And could I access height/width as let mystring = array[0][0] and 1/2 as let myfloat = array[0][1]
let mystring = array[0].0 and let myfloat = array[0].1
Awesome! Thank you
0

You should use a custom struct if you want to store various types. This has the added benefit of allowing you to access those values with a meaningful name instead of just an index. Use an array of tuples and .map(Record.init) to initializes the array of structures.

struct Record {
    var string: String
    var float: Float
}

var records = [("height",  1), ("width", 2)].map(Record.init)

print(records[0].string)  // "height"
print(records[0].float)   // 1.0

1 Comment

This is My API data "publisherPlans": [ [ "Name","Free","Prime"],["Book Sell",9999,9999],["Book Bulk Sell",0,9999]] And I want To fetch all data and set to the View, I am trying this Model struct PublisherPlansModel: Codable { let publisherPlans: [[String]] }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.