string – 如何在Swift中将“Index”转换为“Int”类型?

前端之家收集整理的这篇文章主要介绍了string – 如何在Swift中将“Index”转换为“Int”类型?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想将字符串中包含的字母的索引转换为整数值.尝试读取头文件,但我找不到索引的类型,虽然它似乎符合协议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)

任何帮助表示赞赏.

您需要使用与原始字符串起始索引相关的distanceTo(index)方法
let intValue = letters.startIndex.distanceTo(index)

您还可以使用方法扩展String以返回字符串中第一次出现的字符,如下所示:

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•Swift 3

let letters = "abcdefg"
if let index = letters.characters.index(of: "c") {
    let distance = letters.distance(from: letters.startIndex,to: index)
    print("distance:",distance)
}
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")
}

Xcode 9•Swift 4

let letters = "abcdefg"
if let index = letters.index(of: "c") {
    let distance = letters.distance(from: letters.startIndex,distance)
}
extension String {
    func indexDistance(of character: Character) -> Int? {
        guard let index = index(of: character) else { return nil }
        return distance(from: startIndex,to: index)
    }
}

Swift 4中另一种可能的方法是返回index encodedOffset:

extension String {
    func encodedOffset(of character: Character) -> Int? {
        return index(of: character)?.encodedOffset
    }
    func encodedOffset(of string: String) -> Int? {
        return range(of: string)?.lowerBound.encodedOffset
    }
}
let letters = "abcdefg"
let char: Character = "c"
if let index = letters.encodedOffset(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")
}

猜你在找的Swift相关文章