Search code examples
swiftwatchkittextinput

Result type 'Element' does not match expected type


I am using WatchKit. I've been trying to put together a basic Grocery List app. Here is the code block that I'm stuck on.

@IBAction func getItemNameAndAtToTable() {
    presentTextInputControllerWithSuggestions(suggestions,
        allowedInputMode: WKTextInputMode.Plain,
        completion: { (results) -> Void in
            print(results)
            if results != nil && results!.count > 0 {
                if let result = results[0] as? String {
                    self.groceries.append(result)
                    self.reloadTable()
                }
            }
        })
}

The line if let result = results[0] as? String { is where I'm getting Result type 'Element' does not match expected type. I've looked at tutorials and the Swift docs, and I'm just not seeing the error here. Does anyone know or have any idea why this is happening?

EDIT: Additionally I'm using Xcode 7.0 beta 4 and Watch Simulator 2.0


Solution

  • The docs state what the results parameter is:

    results An array containing the input from the user, or nil if the user canceled the operation. When an array is provided, the value in the array is usually an NSString object representing the text input. The array can also contain an emoji image, packaged as an NSData object. You can use the data object to create a corresponding UIImage object.

    If you look carefully at the method definition, you will notice that it defines results as an optional array [AnyObject]?. You seem to be expecting something like [AnyObject?], which I think is not even possible.

    The array itself is optional, but array elements can of course not be nil. Therefore your cast

    results[0] as? String 
    

    does not really make sense. It should be

    results.first as! String
    

    if you are sure you are not having Emoji data in the array.