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

前端之家收集整理的这篇文章主要介绍了string – 如何将“Index”转换为Swift中的“Int”类型?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
参见英文答案 > Finding index of character in Swift String2
我想将字符串中包含的字母的索引转换为整数值。尝试读取头文件,但是我找不到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")
}
原文链接:https://www.f2er.com/swift/320330.html

猜你在找的Swift相关文章