๐ŸŽ iOS/Swift

[Swift] ์ปฌ๋ ‰์…˜ ํƒ€์ž… | Array, Dictionary, Set

- Array: ์ˆœ์„œ๊ฐ€ ์žˆ๋Š” ๋ฆฌ์ŠคํŠธ ์ปฌ๋ ‰์…˜

 

var integers: Array<Int> = Array<Int>()
integers.append(1)
integers.append(100)
//integers.append(101.1) // ์˜ค๋ฅ˜

integers.contains(100) // true

integers.remove(at:0) // 0๋ฒˆ ์ธ๋ฑ์Šค์˜ ๊ฐ’ ์‚ญ์ œ
integers.removeLast()
integers.removeAll()

integers.count

// Array<Double>์™€ [Double]์€ ๋™์ผํ•œ ํ‘œํ˜„
var doubles: Array<Double> = [Double]()

var strings: [String] = [String]()

var characters: [Character] = []

// let์„ ์‚ฌ์šฉํ•˜์—ฌ ๋ถˆ๋ณ€ Array ์ƒ์„ฑ
let immutableArray = [1,2,3]

 

- Dictionary: ํ‚ค์™€ ๊ฐ’์˜ ์Œ์œผ๋กœ ์ด๋ฃจ์–ด์ง„ ์ปฌ๋ ‰์…˜

 

// Key๊ฐ€ String ํƒ€์ž…์ด๊ณ  Value๊ฐ€ Any์ธ ๋นˆ Dictionary ์ƒ์„ฑ
var anyDictionary: Dictionary<String,Any> = [String:Any]()

// Key์— ํ•ด๋‹น๋˜๋Š” ๊ฐ’ ํ• ๋‹น
anyDictionary["someKey"] = "someValue"

anyDictionary.removeValue(forKey: "someKey")

// empty Dictionary ์ƒ์„ฑ
let emptyDictionary: [String:String] = [:]

// Dictionary ์ดˆ๊ธฐํ™” ์ƒ์„ฑ
let initalizedDictionary: [String:String] = ["name":"yujin","gender":"female"]

let someValue: String = initalizedDictionary["name"] // yujin

 

 

- Set: ์ˆœ์„œ๊ฐ€ ์—†๊ณ , ๋ฉค๋ฒ„๊ฐ€ ์œ ์ผํ•œ ์ปฌ๋ ‰์…˜

 

var integerSet: Set<Int> = Set<Int>()
integerSet.insert(1)
integerSet.insert(100)
integerSet.insert(99)
integerSet.insert(99)

integerSet // {100,99,1}

integerSet.contains(1) //true
integerSet.remove(100)
integerSet.removeFirst()

integerSet.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) //ํ•ฉ์ง‘ํ•ฉ {4, 3, 6, 1, 5, 7, 2}

let sortedUnion: [Int] = union.sorted() // [1, 2, 3, 4, 5, 6, 7]

let intersection: Set<Int> = setA.intersection(setB) // ๊ต์ง‘ํ•ฉ

let subtracting: Set<Int> = setA.subtracting(setB) // ์ฐจ์ง‘ํ•ฉ