Array, Dictionary, Set

·2022년 7월 13일

Swift 기초문법

목록 보기
6/11

Array

순서가 있는 리스트 컬렉션

Dictionary

키와 값의 쌍으로 이루어진 컬렉션

Set

순서가 없고, 멤버가 유일한 컬렉션

//MARK: - Array

var integers: Array<Int> = Array<Int>() // []
integers.append(1) // [1] 요소를 맨 뒤에 추가하는 methods
integers.append(100) // [1, 100]
//integers.append(101.1) Int 타입이 아니니까 오류.

integers.contains(100) //true 포함하고 있는지 판단하는 bool type
integers.contains(99) // false

integers.remove(at:0) // 1 index 위치를 선택
integers.removeLast() // 100 맨 마지막 요소를 제거
integers.removeAll() // [] 모든 멤버를 삭제

integers.count // 0 갯수 세줘~

//integers[0] 비어있는 배열의 0번째 요소로 접근하려 하니까 오류가 발생하고, 강제종료.

//Array<Double>과 [Double]은 동일한 표현.
//빈 Double Array 생성
var doubles: Array<Double> = [Double]() // 괄호가 있어야 생성!
var strings: [String] = [String]()

//[]는 새로운 빈 Array
var characters: [Character] = [] // 동일한 표현들

//let을 사용하여 Array를 선언하면 불변 Array
// append, remove 등등 다 불가능.
let immutableArray = [1, 2, 3]

//MARK: -Dictionary
// Key가 String 타입, Value가 Any인 빈 Dictionary 생성!

var anyDictionary: Dictionary<String, Any> = [String: Any]() // [:]
anyDictionary["someKey"] = "value" 
anyDictionary["anotherKey"] = 100

anyDictionary // ["someKey: "value", "anotherKey": 100]

anyDictionary["someKey"] = "dictionary"
anyDictionary // ["someKey": "dictionary", "anotherKey": 100]

anyDictionary.removeValue(forKey: "anotherKey")

anyDictionary["someKey"] = nil
anyDictionary // [:]

let emptyDictionary: [String: String] = [:]
let initializedDictionary: [String: String] = ["name": "hyun", "gender": "female"]

//let someValue: String = initializedDictionary["name"]
// 오류가 나는 이유는 dictionary에 있는 name의 값이 있을 수도, 없을 수도 있기 때문. 불확실성


//MARK: -Set 중복값 없음을 보장.
var integerSet: Set<Int> = Set<Int>()
integerSet.insert(1)
integerSet.insert(100)
integerSet.insert(99)
integerSet.insert(99)
integerSet.insert(99)
integerSet.insert(99)

integerSet // {100, 99, 1}
integerSet.contains(1) // true
integerSet.contains(2) // false

integerSet.remove(100) // 100 지워
integerSet.removeFirst() // 99 지워

integerSet.count // 1

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) // {2, 4, 5, 6, 7, 3, 1} // union 두 집합을 합쳐
let sortedUnion: [Int] = union.sorted() // [1, 2, 3, 4, 5, 6, 7] 같은 타입의 Array로 변환이 된다1!!
let intersection: Set<Int> = setA.intersection(setB) // {5, 3, 4} 교집합
let subtraction: Set<Int> = setA.subtraction(SetB) // {2, 1} 차집합

야곰의 Swift 기초 강의를 보고 정리한 자료입니다.

profile
어?머지?

0개의 댓글