본문 바로가기

Dev/iOS & SWIFT

[Swift] 컬렉션 타입 | Array | Dictionary | Set

728x90
반응형

컬렉션 타입이란?

값들을 하나로 묶어서 저장 및 표현해줄 수 있게 해주는 데이터 타입

 

  • Array: 순서가 있는 리스트 컬렉션
  • Dictionary: 키와 값의 쌍으로 이루어진 컬렉션
  • Set: 순서가 없고, 멤버가 유일한 컬렉션

 

Array 예제 코드

import Swift

var intArray Array<Int> = Array<Int>()
intArray.append(1) // 요소를 맨 뒤에 추가
intArray.append(100)
//intArray.append(0.1) // 정수 배열이기 때문에 실수를 추가하면 안됨

intArray.contains(100) // 100을 포함하고 있는가? - true 반환
intArray.contains(99) // 99를 포함하고 있는가? - false 반환

intArray.remove(at: 0) // 0번 인덱스에 있는 값을 삭제
intArray.removeLast() // 맨 마지막에 있는 요소를 삭제
intArray.removeAll() // 모든 요소를 삭제

intArray.count // 요소의 개수를 반환


// 다양한 배열(리스트) 표현 방법
var doubles: Array<Double> = [Double]()
var strings: [Strings] = [Strings]()
var characters: [Character] = [] // 빈 Array 생성

let immutableArray = [1, 2, 3] // 불변 Array - 값의 추가나 삭제가 불가능함

 

Dictionary 예제 코드

import Swift

// Key 가 String 타입이고, Value가 Any인 빈 Dictionary 생성
var anyDictionary: Dictionary<String, Any> = [String: Any]()

// 빈 딕셔너리 생성 - let이라서 변경 불가
let emptyDictionary: [String: String] = [:] 

// 순서가 없고, 키와 값의 쌍으로만 이루어져 있음
anyDictionary["someKey"] = "value"
anyDictionary["anotherKey"] = 100

// 불가능한 표현! - 딕셔너리 내에 해당하는 값이 있을지 없을지 모르기 때문
// let someValue: String = anyDictionary["someKey"]

// 키를 이용하여 딕셔너리 내 요소를 삭제하는 방법
anyDictionary.removeValue(forKey: "anotherKey") 
anyDictionary["someKey"] = nil

 

Set 예제 코드

// 빈 정수형 set 생성
var intSet: Set<Int> = Set<Int>()

// 요소 추가
intSet.insert(1)
intSet.insert(100)
intSet.insert(99)
intSet.insert(99) // 중복해서 추가해도, 중복허용을 안하기 때문에 한번만 추가됨

intSet.contains(1) // 요소 포함여부 확인 - true 반환
intSet.contains(2) // 요소 포함여부 확인 - false 반환

intSet.count // 가지고 있는 요소 개수를 확인 가능\

// 합집합, 차집합 등의 연산 가능
let setA: Set<Int> = [1,2,3,4,5]
let setB: Set<Int> = [3,4,5,6,7]

let union: Set<Int> = setA.union(setB) // A+B 합집합
let sortedUnion: [Int] = union.sorted() // 정렬해서 저장
let intersection: Set<Int> = setA.intersection(setB) // 교집합
let subtracting: Set<Int> = setA.subtracting(setB) // A-B 차집합

 

 

본 내용은 부스트코스의 'iOS 프로그래밍을 위한 스위프트 기초' 강의를 토대로 작성되었습니다

728x90
반응형