gpt4 book ai didi

string - 如何在 Swift 中将 "Index"转换为类型 "Int"?

转载 作者:IT王子 更新时间:2023-10-29 04:57:54 25 4
gpt4 key购买 nike

我想将字符串中包含的字母索引转换为整数值。试图读取头文件,但我找不到 Index 的类型,尽管它似乎符合协议(protocol) 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)

感谢任何帮助。

最佳答案

编辑/更新:

Xcode 11 • Swift 5.1 或更高版本

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) }
}

Playground 测试

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")
}

关于string - 如何在 Swift 中将 "Index"转换为类型 "Int"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34540185/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com