Using stringByReplacingCharactersInRange in Swift

2020-02-10 02:17发布

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.

标签: swift
13条回答
Anthone
2楼-- · 2020-02-10 03:18

I created an extension to NSRange the converted to Range<String.Index>

extension NSRange {
    func toRange(string: String) -> Range<String.Index> {
        let startIndex = advance(string.startIndex, location)
        let endIndex = advance(startIndex, length)
        return startIndex..<endIndex
    }
}

So I can create the String like this

let text = textField.text
let newText = text.stringByReplacingCharactersInRange(range.toRange(text), withString: string)

in Swift 2.1 the extension looks like:

extension NSRange {
    func toRange(string: String) -> Range<String.Index> {
        let startIndex = string.startIndex.advancedBy(location)
        let endIndex = startIndex.advancedBy(length)
        return startIndex..<endIndex
    }
}
查看更多
登录 后发表回答