我想将字符串中包含的字母的索引转换为整数值。尝试读取头文件,但是我找不到Index的类型,尽管它似乎符合使用方法(例如distanceto)的ForwardindexType协议。
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)
任何帮助是赞赏。
您需要使用与原始字符串起始索引相关的distanceto(index)方法:let intValue = letters.startIndex.distanceto(index)
您还可以使用一种方法扩展字符串,以返回字符串中第一个出现的字符串,如下所示:
extension String { func indexdistanceOfFirst(character character: Character) -> Int? { guard let index = characters.indexOf(character) else { return nil } return startIndex.distanceto(index) }}let letters = "abcdefg"let char: Character = "c"if let index = letters.indexdistanceOfFirst(character: char) { print("character \(char) was found at position #\(index)") // "character c was found at position #2\n"} else { print("character \(char) was not found")}
Xcode 8 beta 3•Swift 3
extension String { func indexdistance(of character: Character) -> Int? { guard let index = characters.index(of: character) else { return nil } return distance(from: startIndex,to: index) }}let letters = "abcdefg"let char: Character = "c"if let index = letters.indexdistance(of: char) { print("character \(char) was found at position #\(index)") // "character c was found at position #2\n"} else { print("character \(char) was not found")}总结
以上是内存溢出为你收集整理的string – 如何将“Index”转换为Swift中的“Int”类型?全部内容,希望文章能够帮你解决string – 如何将“Index”转换为Swift中的“Int”类型?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)