본문 바로가기

Swift

Swift 기초 문법 / 컬렉션 타입

컬렉션 타입

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

 

Array

Array는 멤버가 순서(인덱스)를 가진 리스트 형태의 컬렉션 타입입니다.

Array 선언 및 생성

// 빈 Int Array 생성
var integers: Array<Int> = Array<Int>()

// 같은 표현
// var integers: Array<Int> = [Int]()
// var integers: Array<Int> = []
// var integers: [Int] = Array<Int>()
// var integers: [Int] = [Int]()
// var integers: [Int] = []
// var integers = [Int]()

Array 활용

integers.append(1)
integers.append(100)

// Int 타입이 아니므로 Array에 추가할 수 없습니다
//integers.append(101.1)

print(integers)	// [1, 100]

// 멤버 포함 여부 확인
print(integers.contains(100)) // true
print(integers.contains(99)) // false

// 멤버 교체
integers[0] = 99

// 멤버 삭제
integers.remove(at: 0)
integers.removeLast()
integers.removeAll()

// 멤버 수 확인
print(integers.count)

// 인덱스를 벗어나 접근하려면 익셉션 런타임 오류발생
//integers[0]

let을 사용하여 Array 선언시 불변 Array 가 됩니다

let immutableArray = [1, 2, 3]

// 수정이 불가능한 Array이므로 멤버를 추가하거나 삭제할 수 없습니다
//immutableArray.append(4)
//immutableArray.removeAll()

 

Dictionary 

Dictionary키 와 값으로 이루어진 컬렉션 타입 (Java의 Map과 비슷하죠 ?)

Dictionary 생성

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

//같은 표현
//var anyDictionary : Dictonary<String , Any> = Dictionary<String, Any>()
//var anyDictionary : Dictonary<String , Any> = [:]
//var anyDictionary : [String: Any] = Dictionary<String , Any> ()
//var anyDictionary : [String: Any] = [String: Any]()
//var anyDictionary : [String: Any] = [:]
//var anyDictionary = [String: Any]()

Dictionary 활용

anyDictionary["someKey"] = "Value"
anyDictionary["anotherKey"] = 100

print(anyDictionary)		//출력 값 : ["someKey" : "Value" , "anotherKey" , 100]

//키에 해당하는 값 변경
anyDictionary["someKey"] = "dictionary"

print(anyDictionary)		//출력 값 : ["someKey" : "dictionary" , "anotherKey" , 100]

//키에 해당하는 값 제거
anyDictionary.removeValue(forKey: "anotherKey")
anyDictionary["someKey"] = nil
print(anyDictionary)		

마찬가지로 let을 사용하여 Dictionary를 선언하면 불변 Dictionary가 됩니다

let emptyDictionary: [String,String] =[:]
let initalizedDictionary: [String,String] = ["name":"seok" , "gender":"male"]

//불변 Dictionary이므로 값 변경 불가
//emptyDictionary ["key"] = "value"

키에 해당하는 값을 다른 변수나 상수에 할당하고자 할 때는 옵셔널과 타입 캐스팅 파트에서 다룹니다

//"name"이라는 키에 해당하는 값이 없을 수 있으므로
//String 타입의 값이 나올 것이라는 보장이 없다.
//컴파일 오류 발생

let someValue:String = initalizedDictiory["name"]

 

Set

Set은 순서가 없고, 멤버가 유일한 것을 보장하는 컬렉션 타입

Set의 선언과 생성

// 빈 Int Set 생성
var integerSet : Set<Int> = Set<Int> ()
integerSet.insert(1)
integerSet.insert(100)
integerSet.insert(99)
integerSet.insert(99)
integerSet.insert(90)

print(integerSet)	//[100,99,90,1]
print(integerSet.contains(1))	//true
print(integerSet.contains(2))	//false

integerSet.remove(100)
integerSet.removeFirst()

print(integerSet.count)	//2

Set은 집합 연산에 많이 활용됨

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)
print(union)		//결과 : [2,4,5,6,7,3,1]

//합집합 오름차순
let sortedUnion: [Int] = union.sorted()
print(sortedUnion)	//[1,2,3,4,5,6,7]

//교집합
let intersection: Set<Int> = setA.intersection(setB)
print(intersection)	//[5,3,4]

//차집합
let subtracting: Set<Int> = setA.subtracting(setB)
print(subtracting)	//[2,1]

'Swift' 카테고리의 다른 글

Swift 기초 문법 / 변수 , 상수 , 기초 데이터 타입  (0) 2021.05.31
Swift 개념  (0) 2021.05.31