Search code examples
swift3watchkitoption-type

Unwrapping Optional - Apple Watch Text Input


I want to receive some text that has been inputted by the user on an Apple Watch. This is what I have so far:

presentTextInputController(withSuggestions: ["Michael","David","John","Lisa","Mary","Susan","Matthew","James","Jessica","Jennifer","Amanda","Emily","Dylan","Ross","Rupert"], allowedInputMode:   WKTextInputMode.plain) { (arr: [Any]?) in
        playerNames.playerOne = String(describing: arr)
        print(playerNames.playerOne)

    }

This always returns a optional like Optional([Michael])

I want it to return Michael

I have looked around about optionals but can't seem to find an anwser.


Solution

  • You can try this code:

    let suggestions = ["Michael", "David", "John", "Lisa", "Mary", "Susan", "Matthew", "James", "Jessica", "Jennifer", "Amanda", "Emily", "Dylan", "Ross", "Rupert"]
    
    presentTextInputController(withSuggestions: suggestions, allowedInputMode: WKTextInputMode.plain) { (arr: [Any]?) in
        guard let arr = arr, let firstElement = arr.first as? String else { return }
        playerNames.playerOne = firstElement
        print(playerNames.playerOne)
    }
    

    Here are some documents you can refer to: Optional Binding, Guard Statement.