string - multiple - ¿Cómo convertir "Índice" para escribir "Int" en Swift?
swift compare strings (2)
Quiero convertir el índice de una letra contenida dentro de una cadena en un valor entero.
Intenté leer los archivos de encabezado pero no puedo encontrar el tipo de
Index
, aunque parece ajustarse al protocolo
ForwardIndexType
con métodos (por ejemplo,
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)
Cualquier ayuda es apreciada.
editar / actualizar:
Xcode 10.2.x • Swift 5 o posterior
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 desea implementarlo como un método de instancia 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)
}
}
Prueba de patio de recreo
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 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")
}
Vieja respuesta
Debe usar el método distanceTo (index) en relación con el índice de inicio de cadena original:
let intValue = letters.startIndex.distanceTo(index)
También puede extender String con un método para devolver la primera aparición de un carácter en una cadena de la siguiente manera:
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")
}
Swift 4
var str = "abcdefg"
let index = str.index(of: "c")?.encodedOffset // Result: 2
Nota: Si la cadena contiene los mismos caracteres múltiples, solo obtendrá el más cercano desde la izquierda
var str = "abcdefgc"
let index = str.index(of: "c")?.encodedOffset // Result: 2