Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

UITextChecker in Swift

I am trying to use UITextChecker in my Swift project.

The code below has an error on the last line. Any ideas where I'm going wrong? Thanks

var checker:UITextChecker = UITextChecker()
        var textLength = countElements(textView.text)
        var checkRange:NSRange = NSMakeRange(0, textLength)

        var misspelledRange:NSRange = checker.rangeOfMisspelledWordInString(textView.text, range: checkRange, startingAt: checkRange.location, wrap: false, language: "en_Us")

        var arrGuessed:NSArray = checker.guessesForWordRange(misspelledRange, inString: textView.text, language: "en_US")!

        var correctedStr = textView.text.stringByReplacingCharactersInRange(misspelledRange, withString: arrGuessed.objectAtIndex(0))

The error is:

'NSRange' is not convertible to 'Range<String.index>'

3 Answers

try

var correctedStr = textAsNSString.stringByReplacingCharactersInRange(misspelledRange, withString: arrGuessed.objectAtIndex(0) as String)

That fixes it. Thanks

cool glad I could help

try removing :NSRange from mispelled range. I believe Range is its own type in swift and it seems like the method on the last line is expecting a Range, not NSRange:

var misspelledRange = checker.rangeOfMisspelledWordInString(textView.text, range: checkRange, startingAt: checkRange.location, wrap: false, language: "en_Us")

It is still showing the same error.

alright rangeofMisspelledWordsinString does indeed return an NSRange.

looking on stack overflow it seems like you have to convert the text thats in the textField to an NSString first:

let textAsNSString = textField.text as NSString
var correctedStr = textAsNSString.stringByReplacingCharactersInRange(misspelledRange, withString: arrGuessed.objectAtIndex(0))

The error has not changed to :

'AnyObject' is not convertible to 'String'

It is now under the objectAtIndex part. Do I need to specify that 'arrGuessed' is a string array?