swift5 기준, array에서 string으로 바꾸고자 할 때 사용할 수 있는 방법들
기본적으로 arrayName.joined(separator: "")의 코드를 사용하는데
각각의 상황에 따라 조금씩 다르다.
Turning an array of Characters into a String with no separator:
let characterArray: [Character] = ["J", "o", "h", "n"]
let string = String(characterArray)
print(string)
// prints "John"
Turning an array of Strings into a String with no separator:
let stringArray = ["Bob", "Dan", "Bryan"]
let string = stringArray.joined(separator: "")
print(string)
// prints: "BobDanBryan"
Turning an array of Strings into a String with a separator between words:
let stringArray = ["Bob", "Dan", "Bryan"]
let string = stringArray.joined(separator: " ")
print(string)
// prints: "Bob Dan Bryan"
Turning an array of Strings into a String with a separator between characters:
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"
Turning an array of Floats into a String with a separator between numbers:
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"
'iOS > swift' 카테고리의 다른 글
swift - Array & Dictionary (basic) (0) | 2021.08.26 |
---|---|
swift - Optional (basic) (0) | 2021.08.25 |
swift - Split vs Components (문자열을 특정 separator로 나눠서 배열에 리턴) (0) | 2021.08.12 |
swift - Struct vs Class (0) | 2021.07.22 |
Swift - Class & Inheritance (0) | 2021.07.19 |