user4331904
user4331904

Reputation:

Swift Array declaration/Type Annotation

I have some code that determines which array to pass to another variable

var x:[Float]
x = someArrayOfFloats
y = x

However currently this present the error

Cannot assign value of type '[Float]' to type '(Float, Float, Float, Float, Float, Float, Float, Float, Float, Float, Float, Float, Float, Float, Float, Float, Float, Float, Float, Float, Float, Float, Float, Float, Float, Float, Float, Float, Float, Float)'

Where float is repeated for the length of the chosen array (I presume).

I've also tried declaring x like so

var x

however this presents

Type annotation missing in pattern

The arrays that will appear in y are of variable length: How might I declare x correctly so it will compile? Must I give it the max length of all arrays? Thanks for your help.

Upvotes: 1

Views: 2769

Answers (2)

Frank Minyon
Frank Minyon

Reputation: 126

It looks like you're trying to assign an array with float values to a [Float] type. If you want to assign Float values to a Float array, you have to declare the x variable in a different manner.

Try this

var x : Array = [Float()]
x = someArrayOfFloats
y = x

Example

var pi : Float = 22/7
var x : Array = [Float()]
x = [pi, pi]
print(x)

Output

[3.14285707, 3.14285707]

Upvotes: 0

Sweeper
Sweeper

Reputation: 274413

I think the problem lies in your y variable. You must have declared your y this way:

var y = (1, 3, 4, 5, 5)

What I want to point out here is that you used () to denote an array literal, which is wrong. () are used for tuple literals. You should use [] instead:

var y = [1, 3, 4, 5, 5]

Upvotes: 1

Related Questions