array created with optional

93 Views Asked by At

I am declaring a array:

var array:[String] = []

assigning values:

array.append(uniqueId as String)

and then pass it to a function:

static var levels_array : [String] = []
class func setLevelsArray(arr:[String])
{
    GamePrefrences.levels_array = arr
    println(GamePrefrences.levels_array)
}

My problem is that when i print the array i get:

[Optional(88868658), Optional(112051080), Optional(95274974)]

Why is that optional? i only want Strings in the array so why is "optional" added?

I come from Java can someone explain why optional is created and how to remove it

2

There are 2 best solutions below

3
On BEST ANSWER

Very likely the actual strings are "Optional(88868658)", etc. You have probably created this strings from an optional accidentally. In the above code, you definitely have an array of strings, not an array of optionals, and when you print an array of strings, they don't include the double-quotes (which can be confusing).

It may is happening here:

array.append(uniqueId as String)

What type is uniqueId? as is not used to convert types. It's just used to cast them if possible (though this should really fail if that's the case; so I'm suspecting you're doing a string interpolation somewhere).

0
On

The Strings themselves are not optional -- the uniqueId is. Basically, optionals mean that a stored value may or may not exist.

I'd recommend using an if let statement to unwrap your optional uniqueID before converting it into a String so the program in fact knows that the optional exists before storing it as a String, ex:

if let uniqueId = uniqueId {
   array.append(uniqueId as String)
}