스위프트 배열을 문자열로 어떻게 변환합니까?


353

프로그래밍 방식으로 수행하는 방법을 알고 있지만 기본 제공 방법이 있다고 확신합니다.

내가 사용한 모든 언어에는 배열과 문자열을 연결하거나 print () 함수 등에 전달하려고 할 때 뱉어 질 객체 모음에 대한 일종의 기본 텍스트 표현이 있습니다. Apple의 Swift 언어 배열을 쉽게 문자열로 변환하는 기본 제공 방법이 있습니까? 아니면 배열을 문자열로 지정할 때 항상 명시해야합니까?


3
스위프트 4 : array.description 또는 사용자 정의 구분 기호를 원하는 경우array.joined(separator: ",")
— Jonathan Solorzano

답변:


697

배열에 문자열이 포함 된 경우 String의 join메소드를 사용할 수 있습니다 .

var array = ["1", "2", "3"]

let stringRepresentation = "-".join(array) // "1-2-3"

에서 스위프트 2 :

var array = ["1", "2", "3"]

let stringRepresentation = array.joinWithSeparator("-") // "1-2-3"

특정 구분 기호 (하이픈, 공백, 쉼표 등)를 사용하려는 경우에 유용 할 수 있습니다.

그렇지 않으면 description속성을 사용 하여 배열의 문자열 표현을 반환 할 수 있습니다 .

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

힌트 : Printable프로토콜을 구현하는 모든 객체 에는 description속성이 있습니다. 자신의 클래스 / 구조체에서 해당 프로토콜을 채택하면 인쇄를 친숙하게 만듭니다.

에서 스위프트 3

  • join해진다 joined예[nil, "1", "2"].flatMap({$0}).joined()
  • joinWithSeparator가된다 joined(separator:)(문자열의 배열 만 가능)

에서 스위프트 4

var array = ["1", "2", "3"]
array.joined(separator:"-")

2
@Andrej : 1.2와 2.0에서 모두 작동합니다. 문자열 배열을 사용하고 있습니까?
— Antonio

1
안토니오, 미안, 내 나쁜 어레이에 문제가있었습니다. 이제 솔루션이 작동하는지 확인할 수 있습니다. :)
— Andrej

12
"-".join(array)Swift 2, Xcode 7 Beta 6에서 더 이상 사용할 수 없습니다.array.joinWithSeparator("-")
— Harry Ng

87
joinWithSeparator문자열 배열에만 사용할 수 있습니다. 다른 객체의 배열이 있으면 map먼저 사용하십시오 . 예 :[1, 2, 3].map({"\($0)"}).joinWithSeparator(",")
— Dmitry

3
@Dmitry 문자열로 변환하기 위해 문자열 보간 솔을 사용하지 마십시오. String에서 이니셜 라이저를 사용하는 것이 훨씬 좋습니다
— Alexander-Reinstate Monica

130

Swift 5를 사용하면 필요에 따라 다음 놀이터 샘플 코드 중 하나를 선택하여 문제를 해결할 수 있습니다.


Characters 배열을 String구분 기호없이 로 변환 :

let characterArray: [Character] = ["J", "o", "h", "n"]
let string = String(characterArray)

print(string)
// prints "John"

Strings 배열을 String구분 기호없이 로 변환 :

let stringArray = ["Bob", "Dan", "Bryan"]
let string = stringArray.joined(separator: "")

print(string) // prints: "BobDanBryan"

단어 사이의 구분 기호를 사용하여 Strings 배열을 로 String바꿉니다.

let stringArray = ["Bob", "Dan", "Bryan"]
let string = stringArray.joined(separator: " ")

print(string) // prints: "Bob Dan Bryan"

문자 사이의 구분 기호를 사용하여 Strings 배열을 로 String바꿉니다.

let stringArray = ["car", "bike", "boat"]
let characterArray = stringArray.flatMap { $0 }
let stringArray2 = characterArray.map { String($0) }
let string = stringArray2.joined(separator: ", ")

print(string) // prints: "c, a, r, b, i, k, e, b, o, a, t"

숫자 사이의 구분 기호를 사용하여 Floats 배열을 로 String바꿉니다.

let floatArray = [12, 14.6, 35]
let stringArray = floatArray.map { String($0) }
let string = stringArray.joined(separator: "-")

print(string)
// prints "12.0-14.6-35.0"

"[1,2,3]"과 같은 문자열이 있습니다. 이것을 배열 [Int]로 쉽게 변환 할 수있는 방법이 있습니까? 쉽게 설명합니다. 설명의 반대가 무엇입니까?
— user2363025

@ user2363025 uni는 JSON 디코더를 사용할 수 있습니다. try JSONDecoder().decode([Int].self, from: Data(string.utf8))
— Leo Dabus

48

Swift 2.0 Xcode 7.0 베타 6 이후 joinWithSeparator()대신 다음을 사용 합니다 join().

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

joinWithSeparator 확장으로 정의됩니다 SequenceType

extension SequenceType where Generator.Element == String {
    /// 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: String) -> String
}

23

스위프트 3

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

1
나는 그것이 ""사랑합니다 ","Swift "]. joined (분리 자 :" ")
— Loebre

15

스위프트 4에서

let array:[String] = ["Apple", "Pear ","Orange"]

array.joined(separator: " ")

11

아무도 Reduce에 대해 언급하지 않았으므로 다음과 같습니다.

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

기능적 프로그래밍의 정신으로


3
작업을 수행하는 좋은 방법, 덕분에 ... 명령 줄의 짧은 끝 추가 : [0,1,1,0].map{"\($0)"}.reduce("",+). 😉
— XLE_22

@ XLE_22[0,1,1,0].map(String.init).joined()
— Leo

8

선택적 / 비 선택적 문자열의 배열을 변경하려면

//Array of optional Strings
let array : [String?] = ["1",nil,"2","3","4"]

//Separator String
let separator = ","

//flatMap skips the nil values and then joined combines the non nil elements with the separator
let joinedString = array.flatMap{ $0 }.joined(separator: separator)


//Use Compact map in case of **Swift 4**
    let joinedString = array.compactMap{ $0 }.joined(separator: separator

print(joinedString)

여기서 flatMap , compactMap 은 배열의 nil 값을 건너 뛰고 다른 값을 추가하여 결합 된 문자열을 제공합니다.


3
@YashBedi Swift 4에서는 flatMap 대신 compactMap을 사용합니다.
— 에이전트 Smith

"$"의 의미는 무엇입니까?
— Augusto

2
@Augusto Swift는 인라인 클로저에 축약 형 인수 이름을 자동으로 제공하며, $ 0, $ 1, $ 2라는 이름으로 클로저의 인수 값을 참조하는 데 사용할 수 있습니다. 여기서 $ 0은 클로저의 첫 번째 String 인수를 나타냅니다.
— 스미스 요원

4

광산은 componentsJoinedByString을 사용하여 NSMutableArray에서 작동합니다.

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

4

Swift 2.2에서는 componentsJoinedByString ( ",")을 사용하기 위해 배열을 NSArray로 캐스트해야 할 수도 있습니다.

let stringWithCommas = (yourArray as NSArray).componentsJoinedByString(",")

그건 그렇고 이것은 단지 objective-c의 빠른 번역입니다.
— Muhammad Zeeshan

3

배열에 빈 문자열을 버리고 싶다면.

["Jet", "Fire"].filter { !$0.isEmpty }.joined(separator: "-")

nil 값도 필터링하려면 다음을 수행하십시오.

["Jet", nil, "", "Fire"].flatMap { $0 }.filter { !$0.isEmpty }.joined(separator: "-")

1
매우 우아합니다, 감사합니다 :)
— CheshireKat

2
let arrayTemp :[String] = ["Mani","Singh","iOS Developer"]
    let stringAfterCombining = arrayTemp.componentsJoinedByString(" ")
   print("Result will be >>>  \(stringAfterCombining)")

결과는 >>> Mani Singh iOS 개발자입니다.


1

설명하는 것과 동일한 Swift는 문자열 보간입니다. JavaScript와 같은 일을 생각하고 있다면 "x" + arraySwift의 해당 내용은 "x\(array)"입니다.

일반적으로 문자열 보간과 Printable프로토콜 간에 중요한 차이점이 있습니다. 특정 클래스 만 준수합니다 Printable. 모든 클래스는 어떻게 든 문자열 보간 될 수 있습니다. 일반 함수를 작성할 때 도움이됩니다. Printable수업에 자신을 제한 할 필요는 없습니다 .


1

인쇄 기능을 사용하여 모든 개체를 인쇄 할 수 있습니다

또는 \(name)객체를 문자열로 변환하는 데 사용 합니다.

예:

let array = [1,2,3,4]

print(array) // prints "[1,2,3,4]"

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

1

에 대한 확장을 만듭니다 Array:

extension Array {

    var string: String? {

        do {

            let data = try JSONSerialization.data(withJSONObject: self, options: [.prettyPrinted])

            return String(data: data, encoding: .utf8)

        } catch {

            return nil
        }
    }
}

0

구분 기호는 히브리어 나 일본어와 같은 일부 언어에는 좋지 않습니다. 이 시도:

// Array of Strings
let array: [String] = ["red", "green", "blue"]
let arrayAsString: String = array.description
let stringAsData = arrayAsString.data(using: String.Encoding.utf16)
let arrayBack: [String] = try! JSONDecoder().decode([String].self, from: stringAsData!)

다른 데이터 유형의 경우 :

// Set of Doubles
let set: Set<Double> = [1, 2.0, 3]
let setAsString: String = set.description
let setStringAsData = setAsString.data(using: String.Encoding.utf16)
let setBack: Set<Double> = try! JSONDecoder().decode(Set<Double>.self, from: setStringAsData!)

0

string array list가 있으면 Int로 변환하십시오.

let arrayList = list.map { Int($0)!} 
     arrayList.description

그것은 당신에게 문자열 값을 줄 것입니다


0

모든 요소 유형

extension Array {

    func joined(glue:()->Element)->[Element]{
        var result:[Element] = [];
        result.reserveCapacity(count * 2);
        let last = count - 1;
        for (ix,item) in enumerated() {
            result.append(item);
            guard ix < last else{ continue }
            result.append(glue());
        }
        return result;
    }
}

0

이 시도:

let categories = dictData?.value(forKeyPath: "listing_subcategories_id") as! NSMutableArray
                        let tempArray = NSMutableArray()
                        for dc in categories
                        {
                            let dictD = dc as? NSMutableDictionary
                            tempArray.add(dictD?.object(forKey: "subcategories_name") as! String)
                        }
                        let joinedString = tempArray.componentsJoined(by: ",")

-1

스위프트 3

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    if textField == phoneField
    {
        let newString = NSString(string: textField.text!).replacingCharacters(in: range, with: string)
        let components = newString.components(separatedBy: NSCharacterSet.decimalDigits.inverted)

        let decimalString = NSString(string: components.joined(separator: ""))
        let length = decimalString.length
        let hasLeadingOne = length > 0 && decimalString.character(at: 0) == (1 as unichar)

        if length == 0 || (length > 10 && !hasLeadingOne) || length > 11
        {
            let newLength = NSString(string: textField.text!).length + (string as NSString).length - range.length as Int

            return (newLength > 10) ? false : true
        }
        var index = 0 as Int
        let formattedString = NSMutableString()

        if hasLeadingOne
        {
            formattedString.append("1 ")
            index += 1
        }
        if (length - index) > 3
        {
            let areaCode = decimalString.substring(with: NSMakeRange(index, 3))
            formattedString.appendFormat("(%@)", areaCode)
            index += 3
        }
        if length - index > 3
        {
            let prefix = decimalString.substring(with: NSMakeRange(index, 3))
            formattedString.appendFormat("%@-", prefix)
            index += 3
        }

        let remainder = decimalString.substring(from: index)
        formattedString.append(remainder)
        textField.text = formattedString as String
        return false
    }
    else
    {
        return true
    }
}

-1

질문이 다음과 같은 경우 : tobeFormattedString = [ "a", "b", "c"] 출력 = "abc"

String(tobeFormattedString)


아니요, 작동하지 않습니다. String그렇게 할 수있는 초기화 프로그램이 없습니다. 사용자 지정 확장 프로그램 또는 타사 라이브러리를 사용 중이거나 단순히 잘못 알고 있습니다.
— Eric Aya
당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.