How to remove Optional from String Value Swift

后端 未结 3 713
不思量自难忘°
不思量自难忘° 2020-12-12 06:21

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         


        
相关标签:
3条回答
  • 2020-12-12 07:04

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

    0 讨论(0)
  • 2020-12-12 07:09

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

    0 讨论(0)
  • 2020-12-12 07:19

    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.

    0 讨论(0)
提交回复
热议问题