Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

253
Views
Eliminar los últimos elementos de una colección mientras una condición en Swift

Estoy intentando eliminar "" & " " de la parte posterior de una matriz de cadenas hasta que el último elemento contenga algo de texto, pero mi implementación no detecta " " .

Mi implementación hasta ahora:

 var array = ["A", "B", "", "C", "D", " ", " ", ""] while true { if (array.last == " " || array.last == "") { array.removeLast() } else { break } }

Mi resultado deseado es

 ["A", "B", "", "C", "D"]

, pero mi salida actual es

 ["A", "B", "", "C", "D", " ", " "]

, donde el ciclo while simplemente breaks después de encontrar " "

¿Algún consejo de por qué no detecta el " " ?

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

No sé por qué tienen drop(while:) y no implementaron dropLast(while:) . La siguiente implementación funciona en cualquier colección:

 extension Collection { func dropLast(while predicate: (Element) throws -> Bool) rethrows -> SubSequence { guard let index = try indices.reversed().first(where: { try !predicate(self[$0]) }) else { return self[startIndex..<startIndex] } return self[...index] } }

 "123".dropLast(while: \.isWholeNumber) // "" "abc123".dropLast(while: \.isWholeNumber) // "abc" "123abc".dropLast(while: \.isWholeNumber) // "123abc"

Y extendiendo RangeReplaceableCollection podemos implementar remove(while:) y removeLast(while:) también:

 extension RangeReplaceableCollection { mutating func remove(while predicate: (Element) throws -> Bool) rethrows { guard let index = try indices.first(where: { try !predicate(self[$0]) }) else { removeAll() return } removeSubrange(..<index) } mutating func removeLast(while predicate: (Element) throws -> Bool) rethrows { guard let index = try indices.reversed().first(where: { try !predicate(self[$0]) }) else { removeAll() return } removeSubrange(self.index(after: index)...) } }

 var string = "abc123" string.removeLast(while: \.isWholeNumber) string // "abc" var string2 = "abc123" string2.remove(while: \.isLetter) string2 // "123" var array = ["A", "B", "", "C", "D", " ", " ", ""] array.removeLast { $0 == "" || $0 == " " } array // ["A", "B", "", "C", "D"]
over 4 years ago · Santiago Trujillo Report

0

Mueva su condición a while y asegúrese de verificar la matriz correcta después de la operación.

 var array = ["A", "B", "", "C", "D", " ", " ", ""] while array.last == " " || array.last == "" { array.removeLast() } print(array) // ["A", "B", "", "C", "D"]
over 4 years ago · Santiago Trujillo Report

0

Una forma de resolver esto es invertir la colección (que se hace de forma perezosa) y soltar los elementos no deseados hasta que encuentre los deseados. Luego, invierta la colección nuevamente.

 let array = ["A", "B", "", "C", "D", " ", " ", ""] let filtered = array.reversed().drop(while: { $0.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }).reversed() as [String] print(filtered) // "["A", "B", "", "C", "D"]\n"

Tenga en cuenta que la verificación de " " puede fallar si no es un espacio normal, por ejemplo, un espacio sin interrupciones (punto de control Unicode U+00A0). Este puede ser el problema que está teniendo en primer lugar. Así que recorta la cadena (elimina los caracteres desde el principio y el final solamente) y verifica si el resultado es una cadena vacía.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!