Eu tenho uma série de cordas como esta
let arrayOfString = ["Nancy", "Peter", "Kevin"]
e eu quero unir todos os elementos do array com uma vírgula e um espaço entre eles.
let joinResult = arrayOfString.joined(separator: ", ")
o que me dá
Nancy, Peter, Kevin
minha dúvida é se é possível adicionar a palavra "e" antes do último elemento se array.count> 2. Nesse caso, será
Nancy, Peter, and Kevin
//if arrayOfString = ["Nancy"], only shows Nancy with no comma and space
Obrigado!
Aqui está uma solução
let arrayOfString = ["Nancy", "Peter", "Kevin"]
let joinedString = arrayOfString.dropLast().joined(separator: ", ")
+ (arrayOfString.count > 1 ? " and " : "")
+ (arrayOfString.last ?? "")
print(joinedString) //Nancy, Peter and Kevin
Você também pode definir o acima como uma função
func joinedNames(from array: [String]) -> String {
return array.dropLast().joined(separator: ", ")
+ (array.count > 1 ? " and " : "")
+ (array.last ?? "")
}
e teste assim:
joinedNames(from: ["Nancy", "Peter", "Kevin"]) //"Nancy, Peter and Kevin"
joinedNames(from: ["Nancy", "Peter"]) //"Nancy and Peter"
joinedNames(from: ["Nancy"]) //"Nancy"
joinedNames(from: []) //""
Se você precisa da vírgula Oxford, aqui está a solução:
func joinedNamesWithOxfordComma(from array: [String]) -> String {
return array
.enumerated()
.map {(index, element) in
if index == 0 {
return element
} else if index <= array.count - 2 {
return ", " + element
} else if array.count > 2 {
return ", and " + element
} else {
return " and " + element
}
}.joined()
}
joinedNamesWithOxfordComma(from: ["Nancy", "Peter", "Kevin"]) //"Nancy, Peter, and Kevin"
joinedNamesWithOxfordComma(from: ["Nancy", "Peter"]) //"Nancy and Peter"
joinedNamesWithOxfordComma(from: ["Nancy"]) //"Nancy"
joinedNamesWithOxfordComma(from: []) //""
Este artigo é coletado da Internet.
Se houver alguma infração, entre em [email protected] Delete.
deixe-me dizer algumas palavras