1

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(withPath:
    "Locations").child("Cities").observe(.value, with: { (snapShot) in
        if snapShot.exists() {
            let array:NSArray = snapShot.children.allObjects as NSArray

            for child in array {
                let snap = child as! DataSnapshot

                let cityName = snap.key
                let cityNameString = "\(cityName)"
                if snap.value is NSDictionary {
                    let data:NSDictionary = snap.value as! NSDictionary
                    let lat = data.value(forKey: "lat")
                    let lng = data.value(forKey: "lng")
                    let radius = data.value(forKey: "radius")
                    let latstring = "\(lat)"
                    let lngstring = "\(lng)" 
                    let radiusstring = "\(radius)" 

                    let city = CityObject(name: cityNameString , lat: latstring , lng: lngstring, radius: radiusstring)
                    print("Value is", laststring)  
                    self.selectCity(cityObject: city)
                }                            

            }
        }
    })

after parsing this data i try to print e.g. the latstring and get following outpup:

Value is Optional(52.523553)

my CityObject looks like the following:

class CityObject{
var name: String?
var lat: String?
var lng: String?
var radius: String?

init(name: String?, lat: String?, lng: String?, radius: String?){
    self.name = name
    self.lat = lat
    self.lng = lng
    self.radius = radius
}
slavoo
  • 5,798
  • 64
  • 37
  • 39
Dominik
  • 419
  • 2
  • 6
  • 16
  • Do you mean that you just want to print `52.523553` by itself? You need to be more explicit and clear about what's wrong, and what your ideal output would be – tel Apr 17 '18 at 22:27
  • 1
    Possible duplicate of [What is an optional value in Swift?](https://stackoverflow.com/questions/24003642/what-is-an-optional-value-in-swift) – Fogmeister Apr 18 '18 at 07:44
  • I suggest reading the free book on Swift from Apple. You can download it for free and it covers all the basics like Optionals. Voting to close this as a duplicate question. – Fogmeister Apr 18 '18 at 07:44
  • Check out my solution [here](https://stackoverflow.com/a/75712608/4261600) – 6rchid Mar 12 '23 at 10:54

3 Answers3

4

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 ^^

Pasosta
  • 825
  • 3
  • 13
  • 22
  • Nitpicking Its `nil coalescing` operator not `nill coalescing` :). **Important:** it will check the `nil` value not `null`. `Null` is not `nil` actually. – TheTiger Apr 18 '18 at 07:43
  • @TheTiger Thanks for the nitpicks! That's how people improve ^^. Also, I was thinking that because pure Swift doesn't really have Null, it wouldn't matter with the intent being similar. After seeing your comment however, I did some research and those distinctions would indeed be very important especially if there is a mixture of Swift and Objective-C. Thanks! – Pasosta Apr 18 '18 at 15:53
4

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.

TheTiger
  • 13,264
  • 3
  • 57
  • 82
0

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 "")

Gi0R
  • 1,387
  • 2
  • 13
  • 15