Why is the word Optional being added when I print a string using a dictionary entry as the variable?
Retrieving a value for a given key from a dictionary is always an optional because the key might not exist then the value is nil
. Using String Interpolation "\(...)"
the Optional is included as literal string.
To avoid the literal Optional(...)
in String Interpolation you have to unwrap the optionals preferred in a safe way
if let first = person["first"] as? String, age = person["age"] as? Int {
print("Your first name is \(first) and you are \(age) years old.")
}
Why is a non-optional value printed as optional?
Inside the function your returning an Int
. However the actual signature of your method is Int?
meaning it is in fact an optional and you got it wrong!
Basically your method signature is correct. But when you call the function you're getting an optional as the response and must unwrap it.
print([5,15,512,522].challenge37(count: "5")!) // 1
Additionally had you paid close attention you would have noticed that Xcode must gave you a warning (and solutions to solve it)
Expression implicitly coerced from
Int?
to Any
Xcode gave you the warning because it found out that you're attempting to print an optional and knows that's usually unwanted. Obviously its solution is to unwrap it either through force unwrap or defaulting.
Optional in text view showing when printing
try with if-let statement:
if let result = trans.value(forKey: "page22") {
page22TextView?.text = result
}
Or try with guard statement:
guard let result = trans.value(forKey: "page22") else { return }
page22TextView?.text = String(describing: result)
Or you can force upwrap it like:
let result = trans.value(forKey: "page22")
if result != nil {
page22TextView?.text = result! as! String
}
Or you can follow the way suggested by @MrugeshTank below in answers
Why does SWIFT print Optional(...)
Swift has optional types for operations that may fail. An array index like airports["XYZ"]
is an example of this. It will fail if the index is not found. This is in lieu of a nil
type or exception.
The simplest way to unwrap an optional type is to use an exclamation point, like so: airports["XYZ"]!
. This will cause a panic if the value is nil
.
Here's some further reading.
You can chain methods on option types in Swift, which will early exit to a nil
without calling a method if the lefthand value is nil
. It works when you insert a question mark between the value and method like this: airports["XYZ"]?.Method()
. Because the value is nil
, Method()
is never called. This allows you to delay the decision about whether to deal with an optional type, and can clean up your code a bit.
To safely use an optional type without panicking, just provide an alternate path using an if
statement.
if let x:String? = airports["XYZ"] {
println(x!)
} else {
println("airport not found")
}
Swift Array is printing word optional from my array dont want to force unwrap
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.
Printing value of a optional variable includes the word Optional in Swift
Optional chaining is used here:
let age = self.clientDetail?.getAge()
So return of getAge()
is optional value. Try optional binding:
if let age = age {
println("age.....\(age)")
}
or simply unwrap the age
with age!
, but this will crash your app if age
is nil.
Unable to print without Optional()
So, rather than checking whether something is nil
, and then when you find out it's not, you both force unwrap and force cast it, we can instead pull this value out safely using optional binding and the correct NSUserDefaults
method: stringForKey(_:)
:
if let data = NSUserDefaults.standardUserDefaults().stringForKey("newString") {
print(data)
}
But, your second & third tries shouldn't be showing the string as optional. This playground demonstrates effectively the exact same thing as what you're doing here with NSUserDefaults
.
func optionalFunc() -> Any? {
return "Hello world."
}
print(optionalFunc())
/* unsafe */ print(optionalFunc() as! String!) /* unsafe */
/* unsafe */ print(optionalFunc() as! String) /* unsafe */
/* unsafe */ print(optionalFunc()!) /* unsafe */
if let unwrapped = optionalFunc() as? String {
print(unwrapped)
}
As you can see, only the first case prints the Optional("Hello world.")
string.
Related Topics
Multiple File Upload with Array of Parameters Using Alamofire
Table View Controller Duplicate Itself in iOS Swift
Cgaffinetransform -How to Align Video in Screen Center
How to Change a View from Portrait Mode to Landscape Mode and Lock It
Uialertcontroller Title and Message Not Appearing
Swift/How to Call Delegate with Popviewcontroller
How to Open Amazon App from Within My App
How to Set the Collection View Cell Size Exactly Equal to the Collection View in iOS
Swiftui - Scrollviewreader's Scrollto Does Not Scroll
Swift Save Viewcontroller State Using Coder Beyond App Close
Update Storyboard Constraint Using Code
Xcode 9.3 - Nspredicate Bool Crash
Swiftui Present View Modally via Tabview