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
Tom Coomer
1,331 PointsUITextChecker 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
Stone Preston
42,016 Pointstry
var correctedStr = textAsNSString.stringByReplacingCharactersInRange(misspelledRange, withString: arrGuessed.objectAtIndex(0) as String)
Stone Preston
42,016 Pointstry 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")
Tom Coomer
1,331 PointsIt is still showing the same error.
Stone Preston
42,016 Pointsalright 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))
Tom Coomer
1,331 PointsThe 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?
Tom Coomer
1,331 PointsTom Coomer
1,331 PointsThat fixes it. Thanks
Stone Preston
42,016 PointsStone Preston
42,016 Pointscool glad I could help