Comment convertir un tableau Swift en string?

Je sais comment le faire par programmation, mais je suis sûr qu'il y a un moyen embedded …

Chaque langage que j'ai utilisé a une sorte de représentation textuelle par défaut pour une collection d'objects qu'il crachera lorsque vous essayez de concaténer le tableau avec une string, ou de le passer à une fonction print (), etc. Le langage Swift d'Apple Avoir un moyen embedded de transformer facilement un tableau en string, ou devons-nous toujours être explicites lors de la mise en string d'un tableau?

    Si le tableau contient des strings, vous pouvez utiliser la méthode de join la Ssortingng :

     var array = ["1", "2", "3"] let ssortingngRepresentation = "-".join(array) // "1-2-3" 

    Dans Swift 2 :

     var array = ["1", "2", "3"] let ssortingngRepresentation = array.joinWithSeparator("-") // "1-2-3" 

    Cela peut être utile si vous souhaitez utiliser un séparateur spécifique (hypen, vide, virgule, etc.).

    Sinon, vous pouvez simplement utiliser la propriété description , qui renvoie une représentation sous forme de string du tableau:

     let ssortingngRepresentation = [1, 2, 3].description // "[1, 2, 3]" 

    Astuce: tout object implémentant le protocole Printable a une propriété de description . Si vous adoptez ce protocole dans vos propres classs / structs, vous les rendez également très conviviaux

    Dans Swift 3

    • join devient joined , exemple [nil, "1", "2"].flatMap({$0}).joined()
    • joinWithSeparator devient joined(separator:) (uniquement disponible pour Array of Ssortingngs)

    Avec Swift 3, selon vos besoins, vous pouvez choisir l'un des blocs de code suivants.


    Transformer un tableau de Character en une Ssortingng sans séparateur:

     let characterArray: [Character] = ["J", "o", "h", "n"] let ssortingng = Ssortingng(characterArray) print(ssortingng) // prints "John" 

    Transformer un tableau de Ssortingng en une Ssortingng sans séparateur:

     let ssortingngArray = ["Foo", "Bar", "Baz"] let characterArray = ssortingngArray.flatMap { Ssortingng.CharacterView($0) } //let characterArray = ssortingngArray.flatMap { $0.characters } // also works let ssortingng = Ssortingng(characterArray) print(ssortingng) // prints "FooBarBaz" 

    Transformer un tableau de Ssortingng en Ssortingng avec un séparateur entre les mots:

     let ssortingngArray = ["Bob", "Dan", "Bryan"] let ssortingng = ssortingngArray.joined(separator: " ") print(ssortingng) // prints "Bob Dan Bryan" 

    Transformer un tableau de Ssortingng en Ssortingng avec un séparateur entre les caractères:

     let ssortingngArray = ["car", "bike", "boat"] let ssortingngArray2 = ssortingngArray.flatMap { Ssortingng.CharacterView($0) }.map { Ssortingng($0) } let ssortingng = ssortingngArray2.joined(separator: ", ") print(ssortingng) // prints "c, a, r, b, i, k, e, b, o, a, t" 

    Transformer un tableau de Float en Ssortingng avec un séparateur entre les nombres:

     let floatArray = [12, 14.6, 35] let ssortingngArray = floatArray.flatMap { Ssortingng($0) } let ssortingng = ssortingngArray.joined(separator: "-") print(ssortingng) // prints "12.0-14.6-35.0" 

    Swift 2.0 Xcode 7.0 beta 6 utilise joinWithSeparator() place de join() :

     var array = ["1", "2", "3"] let ssortingngRepresentation = array.joinWithSeparator("-") // "1-2-3" 

    joinWithSeparator est défini comme une extension sur SequenceType

     extension SequenceType where Generator.Element == Ssortingng { /// Interpose the `separator` between elements of `self`, then concatenate /// the result. For example: /// /// ["foo", "bar", "baz"].joinWithSeparator("-|-") // "foo-|-bar-|-baz" @warn_unused_result public func joinWithSeparator(separator: Ssortingng) -> Ssortingng } 

    Swift 3

     ["I Love","Swift"].joined(separator:" ") // previously joinWithSeparator(" ") 

    Dans Swift 2.2, vous devrez peut-être convertir votre tableau en NSArray pour utiliser componentsJoinedBySsortingng (",")

     let ssortingngWithCommas = (yourArray as NSArray).componentsJoinedBySsortingng(",") 

    Mine fonctionne sur NSMutableArray avec componentsJoinedBySsortingng

     var array = ["1", "2", "3"] let ssortingngRepresentation = array.componentsJoinedBySsortingng("-") // "1-2-3" 
     let arrayTemp :[Ssortingng] = ["Mani","Singh","iOS Developer"] let ssortingngAfterCombining = arrayTemp.componentsJoinedBySsortingng(" ") print("Result will be >>> \(ssortingngAfterCombining)") 

    Le résultat sera >>> Mani Singh iOS Developer

    Puisque personne n'a mentionné réduire, voici:

     [0,1,1,0].map{"\($0)"}.reduce(""){$0+$1}//"0110" 

    Dans l'esprit de la functional programming 🤖

    Dans Swift 4

     let array:[Ssortingng] = ["Apple", "Pear ","Orange"] array.joined(separator: " ") 

    Le Swift équivalent à ce que vous décrivez est l'interpolation de string. Si vous pensez à des choses comme JavaScript faisant "x" + array , l'équivalent dans Swift est "x\(array)" .

    En règle générale, il existe une différence importante entre l'interpolation de string et le protocole Printable . Seules certaines classs sont compatibles avec Printable . Chaque class peut être interpolée en quelque sorte. C'est utile lors de l'écriture de fonctions generics. Vous n'êtes pas obligé de vous limiter aux classs Printable .

    Pour modifier un tableau de strings facultatives / non facultatives

     //Array of optional Ssortingngs let array : [Ssortingng?] = ["1",nil,"2","3","4"] //Separator Ssortingng let separator = "," //flatMap skips the nil values and then joined combines the non nil elements with the separator let joinedSsortingng = array.flatMap{ $0 }.joined(separator: separator) print(joinedSsortingng) 

    Ici, flatMap ignore les valeurs nulles du tableau et ajoute les autres valeurs pour donner une string jointe.

    Vous pouvez imprimer n'importe quel object en utilisant la fonction d'printing

    ou utilisez \(name) pour convertir n'importe quel object en string.

    Exemple:

     let array = [1,2,3,4] print(array) // prints "[1,2,3,4]" let ssortingng = "\(array)" // ssortingng == "[1,2,3,4]" print(ssortingng) // prints "[1,2,3,4]" 

    Créer une extension pour un Array :

     extension Array { var ssortingng: Ssortingng? { do { let data = try JSONSerialization.data(withJSONObject: self, options: [.prettyPrinted]) return Ssortingng(data: data, encoding: .utf8) } catch { return nil } } } 

    POUR SWIFT 3:

     func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementSsortingng ssortingng: Ssortingng) -> Bool { if textField == phoneField { let newSsortingng = NSSsortingng(ssortingng: textField.text!).replacingCharacters(in: range, with: ssortingng) let components = newSsortingng.components(separatedBy: NSCharacterSet.decimalDigits.inverted) let decimalSsortingng = NSSsortingng(ssortingng: components.joined(separator: "")) let length = decimalSsortingng.length let hasLeadingOne = length > 0 && decimalSsortingng.character(at: 0) == (1 as unichar) if length == 0 || (length > 10 && !hasLeadingOne) || length > 11 { let newLength = NSSsortingng(ssortingng: textField.text!).length + (ssortingng as NSSsortingng).length - range.length as Int return (newLength > 10) ? false : true } var index = 0 as Int let formattedSsortingng = NSMutableSsortingng() if hasLeadingOne { formattedSsortingng.append("1 ") index += 1 } if (length - index) > 3 { let areaCode = decimalSsortingng.subssortingng(with: NSMakeRange(index, 3)) formattedSsortingng.appendFormat("(%@)", areaCode) index += 3 } if length - index > 3 { let prefix = decimalSsortingng.subssortingng(with: NSMakeRange(index, 3)) formattedSsortingng.appendFormat("%@-", prefix) index += 3 } let remainder = decimalSsortingng.subssortingng(from: index) formattedSsortingng.append(remainder) textField.text = formattedSsortingng as Ssortingng return false } else { return true } }