我希望将包含在字符串中的字母的索引转换为整数值。尝试阅读头文件,但是我找不到Index
类型,尽管它似乎符合协议ForwardIndexType
并具有方法(例如distanceTo
)。
var letters = "abcdefg"
let index = letters.characters.indexOf("c")!
// ERROR: Cannot invoke initializer for type 'Int' with an argument list of type '(String.CharacterView.Index)'
let intValue = Int(index) // I want the integer value of the index (e.g. 2)
感激所有的帮助。
let index = letters.characters.index(of: "c")
下一行let int_index = letters.characters.distance(from: letters.startIndex, to: index)
翻译: Swift 3:let index = letters.characters.index(of: "c")
意思是在字符串letters
中找到字符 "c" 的位置。接下来的一行代码:let int_index = letters.characters.distance(from: letters.startIndex, to: index)
将字符 "c" 的位置index
和字符串letters
的起始位置letters.startIndex
之间的距离转换为整数型。 - Viktor