Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make an array of certain size in Swift 4?

Tags:

arrays

swift

How do I make a simple array of say 1000 floats? I have tried this:

var computeArray = Array<Float>(repeating: nil, count:1000)

and get

Type of expression is ambiguous without more context

I also tried this and got the same thing:

var computeArray = [Float](repeating: nil, count:1000)

It's so simple but I can't get it to work. These are basically the same as examples I've found online. Has something changed with the most recent Swift 4?

like image 385
Bob S Avatar asked Sep 30 '17 19:09

Bob S


2 Answers

Swift is a type-safe language. This essentially means that you can't store a value of some other type (here nil) in a variable/ constant of a particular type (here Float).

So, if you want to store nil values in an array, declare its element type as optional (here Float?).

var computeArray = [Float?](repeating: nil, count:1000)

or

var computeArray = Array<Float?>(repeating: nil, count:1000)
like image 195
Nilanshu Jaiswal Avatar answered Oct 11 '22 22:10

Nilanshu Jaiswal


Try this.

var computeArray: Array<Float> = Array(repeating: 0, count: 1000)

or with nils

var computeArray: Array<Float?> = Array(repeating: nil, count: 1000)
like image 29
Bilal Avatar answered Oct 11 '22 22:10

Bilal