3

My array: var savedDataArray: Array<String>? = NSUserDefaults.standardUserDefaults().objectForKey("savedDataArray") as? Array<String>

console prints Optional(["75500.0", "2.19351e+08"]) I do not want the word "optional" or the braces

Force unwrapping var savedDataArray Array<String>! stops the word "optional" appearing however my array may be nil so dont I dont want to do this ( and the braces are still present)

This is not the same as the following answers as they all suggest foce unwrapping

Printing value of a optional variable includes the word "Optional" in Swift

How to print a string from plist without “Optional”?

Swift giving Optional(3) instead of 3 for .toInt

Community
  • 1
  • 1
JSA986
  • 5,870
  • 9
  • 45
  • 91

4 Answers4

4

You can pass it to println as ImplicitlyUnwrappedOptional:

var array1:[String]? = ["foo", "bar"]
var array2:[String]? = nil

println(array1) // -> Optional(["foo", "bar"])
println(array2) // -> nil
println(array1 as [String]!) // -> [foo, bar]
println(array2 as [String]!) // -> nil
rintaro
  • 51,423
  • 14
  • 131
  • 139
1

If you print out an optional, you will always have Optional(...) in there. The only way to lose that is to unwrap. That's the only solution.

If you are worried about nil values, check for nil and then unwrap.

Sulthan
  • 128,090
  • 22
  • 218
  • 270
1

You can use ?? like this if it's ok to see no difference between nil and an empty array.

var array: [String]? = ["A", "B"]
println(array ?? []) // Prints "[A, B]"
array = nil
println(array ?? []) // Prints "[]"
Yoichi Tagaya
  • 4,547
  • 2
  • 27
  • 38
0

Its because it is an optional. You have to unwrap.

You can force unwrap:

println(myText!);

or check against a nil first

myText : String = myText ?? ""
println(myText)
Michael Voznesensky
  • 1,612
  • 12
  • 15