상세 컨텐츠

본문 제목

[Swift] 컬렉션 타입 - Array, Dictionary, Set

SWIFT

by 옹홍 2021. 1. 31. 00:25

본문

1. Array - 순서가 있는 리스트 컬렉션

맴버가 순서를 가지기 때문에, index를 통해 접근을 하기 쉽다.

<Array 선언 및 생성>

  • var integers: Array<Int> = Array
  • 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 관련 함수>

.append - 마지막에 요소 추가

.contains

print(integers.contains(100)) - bool - 있다면 true, 없다면 false

.remove(at: 0) - 0번째 인덱스에 있는 요소 삭제

.removeLast() - 마지막 인덱스에 있는 요소 삭제

.removeAll() - 모든 요소 삭제

.count -Int - 몇개가 있는지? 

.isEmpty - bool - 존재하는지 안존재하는지

 

2. Dictionary - 순서가 없는데, 키와 벨류의 쌍으로 이루어진 컬렉션

<생성 및 초기화>

var anyDictionary: Dictionary<String, Any> = [String: Any]()

var anyDictionary: Dictionary<String, Any>= [:]

var anyDictionary: [String, Any] = Dictionary<String, Any>()

var anyDictionary: [String: Any] = [String: Any]()

var anyDictionary: [String: Any] = [:]

var anyDictionary = [String: Any]()

<활용>

// 키에 해당하는값 할당

anyDictionary["Key"] = "value"

anyDictionary["otherkey"] = 100

// 키에 해당하는 값 변경

anyDictionary["someKey"] = "dictionary"

// 키에 해당하는 값 제거

anyDictionary.removeValue(forKey: "otherkey") - 키가 otherkey인 벨류삭제

anyDictionary.["Key"] = nil - Key가 키인 벨류값에 nil을 넣으면서 딕셔너리속 요소 삭제 가능하다

// let을 통한 선언

let emptyDictionary: [String: String] = [:] 

 

3. Set - 중복되지 않은 맴버가 순서없이 존재하는 컬렉션, Array, Dictionar와 다르게 축약형이 존재하지 않음

<생성 및 초기화>

var integerSet: Set<Int> = Set<Int>()

 

// insert: 새로운 멤버 입력

// 동일한 값은 여러번 insert 해도 한번만 저장

integerSet.insert(1)

integerSet.insert(99)

integerSet.insert(99)

integerSet.insert(100)

print(integerSet) // {1, 99, 100}

 

// .contains()로 멤버 포함 여부 확인

 

// remove: 멤버 삭제

remove()

removeFIrst()

<활용>

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]

관련글 더보기

댓글 영역