如何在Swift中将“索引”转换为“ Int”类型?

我想将字符串中包含的字母的索引转换为整数值。尝试读取头文件,但找不到的类型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)

任何帮助表示赞赏。

回答:

编辑/更新:

extension StringProtocol {

func distance(of element: Element) -> Int? { firstIndex(of: element)?.distance(in: self) }

func distance<S: StringProtocol>(of string: S) -> Int? { range(of: string)?.lowerBound.distance(in: self) }

}


extension Collection {

func distance(to index: Index) -> Int { distance(from: startIndex, to: index) }

}


extension String.Index {

func distance<S: StringProtocol>(in string: S) -> Int { string.distance(to: self) }

}


let letters = "abcdefg"

let char: Character = "c"

if let distance = letters.distance(of: char) {

print("character \(char) was found at position #\(distance)") // "character c was found at position #2\n"

} else {

print("character \(char) was not found")

}


let string = "cde"

if let distance = letters.distance(of: string) {

print("string \(string) was found at position #\(distance)") // "string cde was found at position #2\n"

} else {

print("string \(string) was not found")

}

以上是 如何在Swift中将“索引”转换为“ Int”类型? 的全部内容, 来源链接: utcz.com/qa/397471.html

回到顶部