Swift/Tip

Array Extension

까칠코더 2023. 5. 8. 13:00
반응형
  • 배열에서 index로 데이터 안전하게 사용하기
// 배열에서 index로 데이터 안전하게 사용하기
extension Array {
  subscript(safe index: Int) -> Element? {
     return indices ~= index ? self[index] : nil
  }
}

// How to use
let items = [0. 1, 2, 3, 4]
let index = 4
if let value = items[safe: index] {
    print("value : \(value)")
} else {
    print("no value")
}

 

  • 배열 크기별로 분할하기
extension Array {
   func chunked(size: Int) -> [[Element]] {
      stride(from: 0, to: count, by: size).map { Array(self[$0 ..< Swift.min($0 + size, count)]) }
   }
}

// How to use
let items = [0, 1, 2, 3, 4]
let values = items.chunked(size: 2)
// values = [[0, 1], [2, 3], [4]]

 

  • 배열 중복확인하기
extension Array where Element: Hashable {
    // 중복된 항목
    func duplicates() -> [Element] {
        var addedDict = [Element: Bool]()
        return filter({ addedDict.updateValue(true, forKey: $0) != nil })
    }
    
    // 중복 되지 않은 항목
    func noDuplicates() -> [Element] {
        var addedDict = [Element: Bool]()
        return filter({ addedDict.updateValue(true, forKey: $0) == nil })
    }
    
    // 중복된 항목 존재여부
    func isDuplicates() -> Bool {
        Dictionary(grouping: self, by: {$0}).filter { $1.count > 1 }.keys.count > 0
    }
}

// How to use
let items = [0, 1, 2, 3, 4, 0, 2, 5]
print(items.duplicates()) // [0, 2]
print(items.noDuplicates()) // [0, 1, 2, 3, 4, 5]
print(items.isDuplicates()) // true

 

 

반응형