[Swift] Collection Type

민니·2022년 11월 14일
0

Swift 문법

목록 보기
17/17

Collection Type

  • Array 배열
  • Set 집합
  • Dictionary 딕셔너리
  • 저장되는 모든 데이터의 타입이 동일해야 함!


Array 배열

💡 일련의 순서를 가지고 리스트 형식의 값을 저장

기본값이 있는 배열 만들기

var threeInt = Array(repeating: 0.0, count: 3)
print(threeInt)

// [0.0, 0.0, 0.0]

리터럴을 이용한 배열 생성

  • 리터럴: 값 자체 -> 값이 변수나 상수에 담긴 형태가 아니라 그에 저장되는 값 자체
  • [value1, value2, value3] 형태를 활용
var studentList: [String] = ["Kim", "Lee", "Park"]
print(studentList) // ["Kim", "Lee", "Park"]
  • 더 간단하게 표현할 수 있다!
var myStudentList = ["Kim", "Lee", "Park"]
print(myStudentList) // ["Kim", "Lee", "Park"]

배열 접근/수정

  • 배열의 원소 개수 확인
var studentList: [String] = ["Kim", "Lee", "Park"]
print(studentList.count) //3
  • 배열이 비었는지 확인
var studentList: [String] = ["Kim", "Lee", "Park"]
print(studentList.isEmpty) //false

var emptyList = [String]()
print(emptyList.isEmpty) //true
  • 배열에 원소 추가
var studentList: [String] = ["Kim", "Lee", "Park"]
print(studentList) // ["Kim", "Lee", "Park"]

studentList.append("Moon")
print(studentList) // ["Kim", "Lee", "Park", "Moon"]

studentList.append(contentsOf: ["Ji", "Sung"])
print(studentList) // ["Kim", "Lee", "Park", "Moon", "Ji", "Sung"]
  • 특정 위치의 원소에 접근 ➡️ 인덱스 활용하기
var studentList: [String] = ["Kim", "Lee", "Park"]
print(studentList[0]) // Kim
var studentList: [String] = ["Kim", "Lee", "Park"]
studentList[0...2] = ["One", "Two", "Three"]
print(studentList) // ["One", "Two", "Three"]
  • 특정 위치에 원소 추가/삭제
var studentList: [String] = ["Kim", "Lee", "Park"]

studentList.insert("Ji", at: 1) // index 1에 Ji 추가
print(studentList) // ["Kim", "Ji", "Lee", "Park"]

studentList.remove(at: 0)
print(studentList) // ["Ji", "Lee", "Park"]

studentList.removeLast()
print(studentList) // ["Ji", "Lee"]

배열 순회

  • for-in loop 활용하기
var studentList: [String] = ["Kim", "Lee", "Park"]

for student in studentList {
    print(student)
}
//Kim
//Lee
//Park
  • 배열 안의 데이터 이외에 인덱스가 필요할 경우 ➡️ enumerated() 메소드 사용
for (index, student) in studentList.enumerated() {
    print(index, student)
}
//0 Kim
//1 Lee
//2 Park


Set 집합

💡 같은 타입의 서로 다른 값을 중복없이 저장하고자 할 때

  • 배열과 매우 유사하지만 순서나 인덱스가 없고 중복된 아이템을 허용하지 않음 ❗️❗️❗️❗️❗️❗️❗️
  • Set은 내부적으로 Hash 연산의 결과값을 이용하여 데이터 저장
    ➡️ Set에 저장되는 데이터는 해시 연산을 할 수 있는 타입이어야 한다! (hashable)

Hash 연산

임의의 입력된 메시지를 고정 길이의 데이터 크기로 변환해 주는 알고리즘

ex) 나눗셈의 나머지 값을 구하는 % 연산
아무리 큰 수일지라도 10으로 나눈 나머지를 구하면 0~9 중 한 자리 길이의 값으로 변환됨
(이 예시는 좋은 해시 알고리즘은 아니니 그냥 이해하는 데만 사용할 것 ^^ ,, ;;)

Hashable

  • 해시 연산을 할 수 있는 타입
  • Swift에서 String, Int, Double, Bool 같은 기본 타입은 기본적으로 hashable

HashValue

Hash 연산을 이용하여 정수로 반환된 값

let name = "Mini"
let job = "Student"
let nickName = "Mini"

print(name.hashValue) // 1317072255611233826
print(job.hashValue) // -3724650629141004882
print(nickName.hashValue) // 1317072255611233826
  • 상수 name과 상수 nickName의 hashValue는 동일함

빈 Set 생성

var letters = Set<Character>()

배열 리터럴을 이용한 Set 생성

var favoriteFoodList = ["Pizza", "Sandwich", "Pasta", "Pizza"]
print(favoriteFoodList) // ["Pizza", "Sandwich", "Pasta", "Pizza"]

var favoriteFood: Set<String> = ["Pizza", "Sandwich", "Pasta", "Pizza"]
print(favoriteFood) // ["Pasta", "Pizza", "Sandwich"]

- Array와 달리 Set은 데이터가 중복없이 저장됨

Set 접근/수정

  • Set 원소 개수 확인
var favoriteFood: Set<String> = ["Pizza", "Sandwich", "Pasta"]
print(favoriteFood.count) // 3
  • Set이 비었는지 확인
var favoriteFood: Set<String> = ["Pizza", "Sandwich", "Pasta"]
print(favoriteFood.isEmpty) // false
  • 원소 추가/삭제
var favoriteFood: Set<String> = ["Pizza", "Sandwich", "Pasta"]
favoriteFood.insert("Salad")
print(favoriteFood)  // ["Sandwich", "Salad", "Pasta", "Pizza"]
var favoriteFood: Set<String> = ["Pizza", "Sandwich", "Pasta"]
let food = favoriteFood.remove("Sandwich")
print(food) // Optional("Sandwich")
print(favoriteFood) // ["Pasta", "Pizza"]
  • 특정 원소에 접근
var favoriteFood: Set<String> = ["Pizza", "Sandwich", "Pasta"]

var food = favoriteFood.contains("Sandwich")
print(food) // true
food = favoriteFood.contains("Salad")
print(food) // false

Set 순회

  • for-in loop을 이용
var favoriteFood: Set<String> = ["Pizza", "Sandwich", "Pasta"]

for food in favoriteFood {
    print(food)
}
//Sandwich
//Pizza
//Pasta

Set 기본 연산

var oddDigits: Set = [1, 3, 5, 7, 9]
let evenDigits: Set = [0, 2, 4, 6, 8]
let singleDigitPrimeNumbers: Set = [2, 3, 5, 7]

a.intersection(b)

  • 양쪽 Set에서 공통되는 아이템만 선택하여 새로운 Set 생성
oddDigits.intersection(evenDigits).sorted()
// []

a.symmetricDifference(b)

  • 양쪽 Set에서 어느 한쪽에만 있는 아이템 선택하여 새로운 Set 생성
oddDigits.symmetricDifference(singleDigitPrimeNumbers).sorted()
// [1, 2, 9]

a.union(b)

  • 양쪽 Set에 있는 모든 아이템 선택하여 새로운 Set 생성
oddDigits.union(evenDigits).sorted()
// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

a.subtracting(b)

  • Set a에서 교집합 아이템을 제외하여 새로운 Set 생성
oddDigits.subtracting(singleDigitPrimeNumbers).sorted()
// [1, 9]

부분집합과 포함관계 판단 연산

let houseAnimals: Set = ["🐶", "🐱"]
let farmAnimals: Set = ["🐮", "🐔", "🐑", "🐶", "🐱"]
let cityAnimals: Set = ["🐦", "🐭"]
let myFarmAnimals: Set = ["🐮", "🐔", "🐑", "🐶", "🐱"]

a == b

farmAnimals == myFarmAnimals // true

a.isSubset(of: b)

  • Set a 전체가 Set b에 포함되는지 판단
houseAnimals.isSubset(of: farmAnimals) // true

a.isSuperset(of: b)

  • Set a가 Set b의 모든 값을 포함하는지 판단
farmAnimals.isSuperset(of: houseAnimals) // true
houseAnimals.isSuperset(of: farmAnimals) // false

a.isStrictSubset(of: b) & isStrictSuperset(of:)

  • 상위 집합인지를 판단하지만 두 집합이 서로 같은 경우 결과값이 false로 반환
farmAnimals.isSuperset(of: houseAnimals) // true
farmAnimals.isStrictSuperset(of: myFarmAnimals) // false

a.isDisjoint(with: b)

  • Set a와 b에 공통된 아이템이 없는 경우 false 반환
farmAnimals.isDisjoint(with: cityAnimals) // true


딕셔너리

💡 고유 키(Key):대응하는 값(Value) 형식으로 데이터를 저장하는 자료형

  • 배열과 매우 유사하지만 인덱스 대신 고유 키를 사용한다는 차이~
  • 키는 중복될 수 없음
  • 키의 타입은 Hash 연산이 가능한 타입이어야 함

빈 딕셔너리 생성

var capital = [String: String]()

리터럴을 이용한 딕셔너리의 생성

var capital = ["KR":"Seoul", "EN":"London", "FR":"Paris"]
print(capital) // ["FR": "Paris", "KR": "Seoul", "EN": "London"]

Dictionary의 접근과 변경

  • 딕셔너리 요소 개수 확인
ar capital = ["KR":"Seoul", "EN":"London", "FR":"Paris"]
print(capital.count) // 3
  • 딕셔너리가 비었는지 확인
var capital = ["KR":"Seoul", "EN":"London", "FR":"Paris"]
print(capital.isEmpty) // false
  • 값 확인
var capital = ["KR":"Seoul", "EN":"London", "FR":"Paris"]
print(capital["KR"]) // Optional("Seoul")
print(capital["JAP"]) // nil
  • 값 할당
var capital = ["KR":"Seoul", "EN":"London", "FR":"Paris"]
capital["JAP"] = "Tokyo"
print(capital) // ["JAP": "Tokyo", "KR": "Seoul", "EN": "London", "FR": "Paris"]

🔗 https://docs.swift.org/swift-book/LanguageGuide/CollectionTypes.html
🔗 https://developer.apple.com/

0개의 댓글