I'm trying to use UITextFieldDelegate in Swift/Xcode6 and I'm struggling with the way I'm supposed to use stringByReplacingCharactersInRange. The compiler error is 'Cannot convert the expression's type 'String' to type '$T8'.
func textField(textField: UITextField!, shouldChangeCharactersInRange range: NSRange, replacementString string: String!) -> Bool
{
let s = textField.text.stringByReplacingCharactersInRange(range:range, withString:string)
if countElements(s) > 0 {
} else {
}
return true
}
Update for Xcode 6 Beta 5: The thing is shouldChangeCharactersInRange gives an NSRange object and we'd need a Swift Range object for stringByReplacingCharactersInRange. Can this still be considered a bug as I don't see why we should still be dealing with NS* objects? The String argument of the delegate method is anyway of a Swift type.
Working & tested
This is a cross-post from this question, but without a way to make a
Range<String.Index>
the Swift-nativeString.stringByReplacingCharactersInRange()
is pretty useless. So, here's a function to generate aRange<String.Index>
:for iOS 8.3 use following code
Here's how to calculate the resulting string in various Swift versions.
Note that all methods use
-[NSString stringByReplacingOccurrencesOfString:withString:]
in exactly the same way, just differing in syntax.This is the preferred way to calculate the resulting string. Converting to a Swift
Range
and use that on a SwiftString
is error prone. Johan's answer for example is incorrect in a couple of ways when operating on non-ASCII strings.Swift 3:
Swift 2.1:
Swift 1 (only left here for reference):
Nothing worked for me except the following: (FYI I'm using Xcode7.0 GM, Swift 2.0, iOS9GM)
As of Swift 4, this is a little simpler, like Alexander Volkov's answer, but without the extension.