Jake Walker
Jake Walker

Reputation: 305

How do I not get optional in the output?

I have a welcome string that says Hello and if the user has entered a firstname when registering and thus it is not equal to nil then it says Hello Jake or whatever. However, on the screen it says "Hello Optional("Jake")". Now I am very new to swift but I do know about the concept force unwrapping. I tried putting an exclamation mark at different points and tried

let personsName = user["FirstName"] as! String

to say it is definitely a string but that didn't work either.

welcomeLabel.text = "Hello"
let user = PFUser.current()!
if let personsName = user["FirstName"] {
    welcomeLabel.text = "Hello " + String(personsName)
}

Upvotes: 1

Views: 79

Answers (3)

marciokoko
marciokoko

Reputation: 4986

Putting a ! or ? doesn't make it any particular type. If you want to make sure it has a value and that it is of the type you want, you need to do so in the declaration of firstName. Declare it as a at ring and give it an initial value.

Upvotes: 0

Khundragpan
Khundragpan

Reputation: 1960

You can cast to String which will unwrap the value

// You user might be like this 
let user:[String: AnyObject?] = ["FirstName": "Joe"]

if let personsName = user["FirstName"] as? String {
  print (  "Hello  \(personsName)")  // Hello  Joe
}

if let personsName2 = user["FirstName"] {
    print ("Hello  \(personsName2)") // Hello  Optional(Joe)

}

Upvotes: 2

PinkeshGjr
PinkeshGjr

Reputation: 8680

Use this code , If you want to do some action while name is empty do it like this

let name = nameTextField.text

    if name.isEmpty {

        let alert = UIAlertController(title: "Error", message: "Please enter a name",
                preferredStyle: UIAlertControllerStyle.Alert)

        alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default,
                handler: nil))

        self.presentViewController(alert, animated: true, completion: nil)
    } else {

        helloLabel.text = "Hello \(name)!"
    }

Upvotes: 0

Related Questions