我正在尝试将Swift 2.3迁移到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>')
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
}
答案 0 :(得分:15)
您可以使用..<
代替...
range
来Range<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)
}