Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
Tags
- tableView
- swift documentation
- SWIFT
- Protocol
- RxCocoa
- swiftUI
- scrollview
- ribs
- map
- UITextView
- clean architecture
- collectionview
- Clean Code
- Human interface guide
- MVVM
- ios
- HIG
- Refactoring
- 애니메이션
- uiscrollview
- 스위프트
- combine
- Observable
- rxswift
- uitableview
- 클린 코드
- Xcode
- 리팩토링
- 리펙토링
- UICollectionView
Archives
- Today
- Total
김종권의 iOS 앱 개발 알아가기
[iOS - swift] 문자열 합치는 방법 (joined vs reduce) 본문
문자열 합치는 방법
- 대표적으로 joined와 reduce가 존재
- joined는 String 배열일 때 separator를 넣어주면서 합쳐주는 기능
extension Array where Element == String {
public func joined(separator: String = "") -> String
}
- reduce는 collection type으로 정의되어 있고 컬렉션을 iteration하면서 합쳐주는 기능
@frozen public struct Array<Element> {
@inlinable public func reduce<Result>(_ initialResult: Result, _ nextPartialResult: (Result, Element) throws -> Result) rethrows -> Result
}
joined와 reduce
- reduce는 collection type으로 추상화된 메소드이고 쓰임이 다양하지만, 문자열을 합칠 때 실수 할 수 있는 부분이 있으므로 joined를 사용할 것
ex) 문자열 배열이 있을 때 콤마를 사용하여 하나의 문자열로 만들어야하는 경우
- reduce를 사용하면 첫 문자의 시작을 ""로 초기화하여 콤마가 첫문자열 apple앞에도 실수로 들어간 코드
- 반면에 joined를 사용하면 직관적으로 의도에 맞게 실수가 적은 코드 관리가 가능
let fruits = ["apple", "banana", "cherry"]
let result = fruits.reduce("") { $0 + "," + $1 }
print(result) // ,apple,banana,cherry
let result2 = fruits.joined(separator: ",")
print(result2) // apple,banana,cherry