web-dev-qa-db-fra.com

Comment convertir "Index" en "Int" dans Swift?

Je veux convertir l'index d'une lettre contenue dans une chaîne en une valeur entière. J'ai tenté de lire les fichiers d'en-tête, mais je ne trouve pas le type pour Index, bien qu'il semble conforme au protocole ForwardIndexType avec des méthodes (par exemple, 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)

Toute aide est appréciée.

68
Christopher

éditer/mettre à jour:

Xcode 10.2.x • Swift 5 ou plus récent

extension Collection where Element: Equatable {
    func indexDistance(of element: Element) -> Int? {
        guard let index = firstIndex(of: element) else { return nil }
        return distance(from: startIndex, to: index)
    }
}
extension StringProtocol {
    func indexDistance(of string: Self) -> Int? {
        guard let index = range(of: string)?.lowerBound else { return nil }
        return distance(from: startIndex, to: index)
    }
}

Xcode 9 • Swift 4

let letters = "abcdefg"

if let index = letters.index(of: "c") {
    let distance = letters.distance(from: letters.startIndex, to: index)
    print("distance:", distance)
}

if let index = letters.range(of: "cde")?.lowerBound {
    let distance = letters.distance(from: letters.startIndex, to: index)
    print("distance:", distance)
}

Si vous souhaitez l'implémenter en tant que méthode d'instance de Collection:

extension Collection where Element: Equatable {
    func indexDistance(of element: Element) -> Int? {
        guard let index = index(of: element) else { return nil }
        return distance(from: startIndex, to: index)
    }
}

extension StringProtocol where Index == String.Index {
    func indexDistance(of string: Self) -> Int? {
        guard let index = range(of: string)?.lowerBound else { return nil }
        return distance(from: startIndex, to: index)
    }
}

Test du terrain de je

let letters = "abcdefg"

let char: Character = "c"
if let distance = letters.indexDistance(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 cde = "cde"
if let distance = letters.indexDistance(of: cde) {
    print("string \(cde) was found at position #\(distance)")   // "string cde was found at position #2\n"
} else {
    print("string \(string) was not found")
}

Xcode 8 • Swift

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

Ancienne réponse

Vous devez utiliser la méthode distanceTo (index) par rapport à l'index de début de chaîne d'origine:

let intValue = letters.startIndex.distanceTo(index)

Vous pouvez également étendre String avec une méthode pour renvoyer la première occurrence d'un caractère dans une chaîne comme suit:

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")
}
69
Leo Dabus

Swift 4

var str = "abcdefg"
let index = str.index(of: "c")?.encodedOffset // Result: 2

Remarque: Si String contient les mêmes caractères multiples, le plus proche sera celui de gauche.

var str = "abcdefgc"
let index = str.index(of: "c")?.encodedOffset // Result: 2
4
Shem Alexis Chavez