iOS Swift - Collection(Array,Dictionary, Set)

longlivedrgn·2022년 8월 22일
0

swift문법

목록 보기
11/36
post-thumbnail

Array

  • array의 기본형
var array = [1,2,3]
  • 정식 문법으로 array를 만들기
let strArray: Array<String>
  • 단축 문법으로 array를 만들기
let strArray2: [String]

Array 만들기

// 빈 array 만들기
let emptyArray: [Int] = []

// 정식 문법으로
let emptyArray2 = Array<Int>()

// 단축 문법으로
let emptyArray3 = [Int]()

// 0 이 열개가 채워진 Int array를 만들기
let zeroArray = [Int](repeating: 0, count: 10)

Inspecting an Array

let nums = [1,2,3]

nums.count //3

nums.isEmpty //false

Accessing Elements

let fruits = ["Apple", "Banana", "Melon"]

fruits[0] //"Apple"
fruits[2] // "Melon"
fruits[0...1] // ["Apple", "Banana"]
fruits[fruits.startIndex] //"Apple"

// endIndex는 마지막 index의 다음 인덱스이다.
fruits[fruits.index(before: fruits.endIndex)] //"Melon"
fruits.first // "Apple"
fruits.last // "Melon"

Adding Element

  • Append / Insert
var alphabet = ["A", "B", "C"]

// append는 배열 마지막에 추가를 한다.
alphabet.append("E") //["A", "B", "C", "E"]

// 같은 type만 넣을 수 있다.

// 두개 이상의 요소를 추가할 때
alphabet.append(contentsOf: ["F", "G"]) //["A", "B", "C", "E", "F", "G"]

alphabet.insert("D", at: 3) //["A", "B", "C", "D", "E", "F", "G"]

alphabet.insert(contentsOf: ["a", "b", "c"], at: 0) //["a", "b", "c", "A", "B", "C", "D", "E", "F", "G"]

// 교체하기
alphabet[0...2] = ["x","y","z"]
alphabet

alphabet.replaceSubrange(0...2, with: ["a","b","c"])
alphabet

alphabet[0...2] = ["z"]
alphabet

Removing Elements

alphabet = ["A", "B", "C", "D", "E", "F", "G"]

// Index를 넘긴다
alphabet.remove(at: 2)
alphabet

alphabet.removeFirst()
alphabet

// 배열 앞부분의 2개를 지운다.
alphabet.removeFirst(2)
alphabet

// 모두 삭제하기
alphabet.removeAll()

// 마지막 배열 삭제하기
alphabet.popLast()

alphabet = ["A", "B", "C", "D", "E", "F", "G"]

// 특별 배열 삭제하기
alphabet.removeSubrange(0...2)
alphabet

alphabet[0...2] = []
alphabet

Comparing Arrays

let a = ["A", "B", "C"]
let b = ["a", "b", "c"]

// 대소문자랑 순서도 비교한다.
a == b
a != b

a.elementsEqual(b)

Finding Elements

let nums = [1,2,3,4,5,6,7,8,9,1,0]

nums.contains(1)

// 짝수가 있는 지 확인해보기
nums.contains { (n) -> Bool in
    return n % 2 == 0
} // true

// 뭐가 가장 빠른 짝수인가?
nums.first { (n) -> Bool in
    return n % 2 == 0
} // 2

// 그러한 짝수의 Index는?
nums.firstIndex { (n) -> Bool in
    return n % 2 == 0
} // 1

nums.lastIndex(of: 1) // 9

Sorting on Array

let nums = [1,2,3,4,5,6,7,8,9,1,0]

// 새로운 배열을 뱉어낸다. -> 원래 있던 배열을 변경시킬수는 없다.
nums.sorted()
nums // [1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 0]

nums.sorted { (a,b) -> Bool in
    return a > b
} // [9, 8, 7, 6, 5, 4, 3, 2, 1, 1, 0]

nums.sorted().reversed()

// 가변 배열
var mutableNums = nums //[1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 0]

// 배열을 직접 변경한다.
mutableNums.sort() //[0, 1, 1, 2, 3, 4, 5, 6, 7, 8, 9]
mutableNums.reverse() //[9, 8, 7, 6, 5, 4, 3, 2, 1, 1, 0]

mutableNums //[9, 8, 7, 6, 5, 4, 3, 2, 1, 1, 0]
mutableNums.swapAt(0, 1) //[8, 9, 7, 6, 5, 4, 3, 2, 1, 1, 0]
mutableNums //[8, 9, 7, 6, 5, 4, 3, 2, 1, 1, 0]

Dictionary

Dictionary -> 정열되어 있지 않다!

  • 기본형
// 기본형
var dict = ["A" : "Apple", "B" : "Banana"]

// 빈 dictionary를 만들자
dict = [:]
  • 정식문법
let dict1 : Dictionary<String, Int>
  • 단축문법
let dict2 : [String : Int]

Creating a Dictionary

let words = ["A" :"Apple", "B": "Banana", "C":"City"]
let emptyDict: [String: String] = [:]
let emptyDict2 = [String: String]()
let emptyDict3 = Dictionary<String, String>()

Inspecting a Dictionary

let words = ["A" :"Apple", "B": "Banana", "C":"City"]
words.count //3
words.isEmpty //false

Accessing Keys and Values

let words = ["A" :"Apple", "B": "Banana", "C":"City"]
words["A"] // "Apple"

// Apple이라는 key는 없다
words["Apple"] // nil

// E라는 key도 없다.
let a = words["E"]

// 기본값 설정하기
let b = words["E", default: "Empty"] //"Empty"

for k in words.keys {
    print(k)
}

for v in words.values {
    print(v)
}


let keys = Array(words.keys) // ["B", "C", "A"]
let values = Array(words.values) // ["Banana", "City", "Apple"]

Adding Keys and Values

var words = [String : String]() // [:]

// A가 key Apple이 value
words["A"] = "Apple"
words["B"] = "Banana"

words.count // 2
words // ["A": "Apple", "B": "Banana"]

// key는 중복될 수 없기에, 변경하기
words["B"] = "Ball"

words // ["A": "Apple", "B": "Ball"]

// 새로운 요소를 추가한다.
words.updateValue("City", forKey: "C")

// 요소 업데이트 하기
words.updateValue("Circle", forKey: "C")
words // ["A": "Apple", "C": "Circle", "B": "Ball"]

Removing Keys and Values

// B를 삭제하기
words["B"] = nil

words

// 존재하지 않는 key를 삭제하면 아무 일이 일어나지 않는다.
words["Z"] = nil

// A : "Apple" 을 없앤다.
words.removeValue(forKey: "A")

// 또 삭제하면 아무일도 일어나지 않는다.
words.removeValue(forKey: "A")

// 전체 삭제하기
words.removeAll()

Finding Elements

// dictionary는 순서가 정해져있지 않기에, 매번 순서가 변화가 된다.
var words = ["A": "Apple", "B" : "Banana", "C": "City"]

// Key가 "B", Value가 "i"포함인 거!
let c: ((String, String)) -> Bool = {
    $0.0 == "B" || $0.1.contains("i")
}

words.contains(where: c) // true

let r = words.first(where: c) // (key "B", value "Banana")
r?.key // "B"
r?.value // "Banana"

// c를 만족시키는 요소들만 뽑아낸다!
words.filter(c) // ["B": "Banana", "C": "City"]

Set

// 중복을 허용한다. -> Array
let array = [1,2,3,3,3,3]
array.count // 6

// 중복허용 하지않음. -> Set
let set: Set<Int> = [1,2,3,3,3,3] // {2, 1, 3}
set.count // 3

Inspecting a Set/Testing for Membership

set.count

set.isEmpty

set.contains(1)

Adding and Removing Elements

var words = Set<String>()

var insertResult = words.insert("Swift")

insertResult.inserted // true
insertResult.memberAfterInsert // "Swift"

// update도 요소를 삽입한다고 생각하면 된다. insert와 유사하다.
var updateResult = words.update(with: "Swift")
updateResult

// 없으면 insert가 된다.
var updateResult1 = words.update(with: "Apple")

// remove를 통하여 삭제하기
words.remove("Swift")

Iterating Collections

  • 기본 꼴은 아래와 같다.
for elment in collection {
	statements
}

Iterating Array

let arr = [1,2,3]

for num in arr {
    print(num)
}

Iterating Set

let set: Set = [1,2,3]
for num in set {
    print(num)
}

Iterating Dictionary

let dict = ["A":1 , "B": 2, "C": 3]
for (key,value) in dict {
    print(key,value)
}

forEach Array

let arr = [1,2,3]
arr.forEach { (num) in
    print(num)
}

forEach Set

let set: Set = [1,2,3]
set.forEach { (num) in
    print(num)
}

forEach Dictionary

let dict = ["A": 1 , "B": 2 ,"C": 3]
dict.forEach { (elem) in
    print(elem.key, elem.value)
}

forEach VS for문

  • for문의 경우 return이 전체 함수 코드에 영향을 주기에 반복이 되다가 중간에 중지가된다.
func withForIn() {
    print(#function)
    let arr = [1,2,3]
    for num in arr {
        print(num)
        // return문은 전체 함수 코드를 중지한다.
        return
    }
}
withForIn() // 1
  • forEach문의 경우, 반복문이 아니므로 return이 코드 블럭 안에서만 발동된다.
func withForeach() {
    print(#function)
    let arr = [1,2,3]
    // forEach의 경우 반복문이 아니기에 return은 closure 코드만 중지한다.
    // 즉, 코드 블록 밖에는 아무영향을 주지 않는다.
    arr.forEach { (num) in
        print(num)
        return
    }
}

withForeach() // 1 2 3

0개의 댓글