Swift3.0无法将'ClosedRange <index>'类型的值转换为'Range <index>'类型

时间:2016-08-17 08:18:43

标签: iphone xcode swift2 swift3 xcode8

我正在尝试将Swift 2.3迁移到3.0并在转换后面临此问题。有什么建议我做错了。

Swift 3.0:

override func setValue(_ value: AnyObject?, forKey key: String) {
    let uppercasedFirstCharacter = String(key.characters.first!).uppercased()
    let range = key.startIndex...key.index(key.startIndex, offsetBy: 0)
    let selectorString = key.replacingCharacters(in: range, with: uppercasedFirstCharacter)

    let selector = NSSelectorFromString("set\(selectorString):")
    let responds = self.responds(to: selector)

    if !responds {
        return
    }
  

错误:

     

let selectorString = key.replacingCharacters(in:range,with:uppercasedFirstCharacter)

Cannot convert value of type 'ClosedRange<Index>' (aka 'ClosedRange<String.CharacterView.Index>') to expected argument type 'Range<Index>' (aka 'Range<String.CharacterView.Index>')

原始代码:Swift 2.3

override func setValue(value: AnyObject?, forKey key: String) {
    let uppercasedFirstCharacter = String(key.characters.first!).uppercaseString

    let range = key.startIndex...key.startIndex.advancedBy(0)
    let selectorString = key.stringByReplacingCharactersInRange(range, withString: uppercasedFirstCharacter)

    let selector = NSSelectorFromString("set\(selectorString):")
    let responds = self.respondsToSelector(selector)

    if !responds {
        return
    }

2 个答案:

答案 0 :(得分:15)

您可以使用..<代替... rangeRange<Index>代替ClosedRange<Index>,在这种情况下调用{{1}不会产生错误(请注意stringByReplacingCharactersInRange(...)增加offsetBy。)

1

现在,我可能错了,但好像你只是希望let range = key.startIndex..<key.index(key.startIndex, offsetBy: 1) // range is now type Range<Index> 成为selectorString的版本,第一个字符是大写的。您的范围解决方案的另一种方法,例如:使用key扩展解决方案,如下所示:

String

答案 1 :(得分:0)

Swift 3 +

override func setValue(_ value: Any?, forKey key: String) {
        let upperCaseFirstCharacter = String(key.characters.first!).uppercased()
        let range = key.startIndex..<key.index(key.startIndex, offsetBy: 1)
        let selectorString = key.replacingCharacters(in: range, with: upperCaseFirstCharacter)

        let selector = NSSelectorFromString("set\(selectorString):")
        let responds = self.responds(to: selector)

        if !responds{
            return
        }
        super.setValue(value, forKey: key)
    }

    init(dictionary: [String: Any]){
        super.init()
        setValuesForKeys(dictionary)
    }