I\'d like to use a String value without the optional extension. I parse this data from firebase using the following code:
Database.database().reference(withP
Just like @GioR said, the value is Optional(52.523553) because the type of latstring is implicitly: String?. This is due to the fact that let lat = data.value(forKey: "lat") will return a String? which implicitly sets the type for lat. see https://developer.apple.com/documentation/objectivec/nsobject/1412591-value for the documentation on value(forKey:)
Swift has a number of ways of handling nil. The three that may help you are, The nil coalescing operator:
??
This operator gives a default value if the optional turns out to be nil:
let lat: String = data.value(forKey: "lat") ?? "the lat in the dictionary was nil!"
the guard statement
guard let lat: String = data.value(forKey: "lat") as? String else {
//Oops, didn't get a string, leave the function!
}
the guard statement lets you turn an optional into it's non-optional equivalent, or you can exit the function if it happens to be nil
the if let
if let lat: String = data.value(forKey: "lat") as? String {
//Do something with the non-optional lat
}
//Carry on with the rest of the function
Hope this helps ^^
That's because your value is actually an optional. You could either do
if let myString = laststring {
print("Value is ", myString)
}
or provide a default value like so
print("Value is ", laststring ?? "")
(in this case the provided default value is "")
Optional
is because you're printing an optional value ?
.
print("Value is", laststring!)
Above code will not print Optional
. But avoid forcecasting and use guard
for safety.
guard let value = lastString else {return}
print("Value is", value)
Or you can use Nil Coalescing operator.
print("Value is", laststring ?? "yourDefaultString")
So in case laststring
is nil
it will print yourDefaultString
.
Important message for you, Use Dictionary
instead of NSDictionary
, use Array
instead of NSArray
this is swift
.