개발 블로그/아이폰개발
[iOS 유용한 메소드] joined() 배열을 텍스트로 나눌때 편한 함수 "," , "-"
snapshot
2020. 5. 29. 11:02
joined()는 이런식으로 배열을 string으로 편하게 return 해주는 메소드이다.
extension Array where Self.Element == String {
/// Returns a new string by concatenating the elements of the sequence,
/// adding the given separator between each element.
///
/// The following example shows how an array of strings can be joined to a
/// single, comma-separated string:
///
/// let cast = ["Vivien", "Marlon", "Kim", "Karl"]
/// let list = cast.joined(separator: ", ")
/// print(list)
/// // Prints "Vivien, Marlon, Kim, Karl"
///
/// - Parameter separator: A string to insert between each of the elements
/// in this sequence. The default separator is an empty string.
/// - Returns: A single, concatenated string.
public func joined(separator: String = "") -> String
}
서버에서 array(배열) sns 연동 정보를 모두 텍스트로 보여주길 원했다.
["카카오", "페이스북", "애플", "네이버"]
["카카오"]
["네이버", "페이스북"]
뭐 이런 경우이다.
", "를 이용하자
사실 하나 있을 때와 여러개 있을 때 if를 하나 더 썼었는데......
간단하게 하자
let snsList = ["카카오", "페이스북", "애플", "이메일", "네이버"]
let resultText = snsList.joined(separator: ", ")
print(resultText)
// "카카오, 페이스북, 애플, 이메일, 네이버\n"
아주 편한 joined()