swift 문법 총정리(3)-Collection Types

Updated:

Collection Types

  • Array
var someInts = Array<Int>()
var someStrings = [String]()

print(someStrings.count)
//0

[]
//빈배열

//배열추가
someStrings.append("aa")
someStrings.append("ccc")
someString.append(3)
//err

print(someStrings)
//["aa","ccc"]

//index 배열 삭제
someString.remove(at: 1)

var removeIndex = 2
//index를 벗어나면 오류발생. 해당 index가 존재하는지 반드시 체크할 필요가 있다.
if someStrings.count - 1 >= removeIndex{
	someStrings.remove(at: removeIndex)
	}
//최대로 사용할 수 있는 인덱스 값
  • Set

Hashable - String, Int , Double, Bool 기본적으로 고유값을 가질 수 있는 타입을 Hashable이라고 한다. 고유값이 있는 형태로서만 사용되는것이 set type. 중복 허용이 기본적으로 안된다.

var strings = Set<String>()
strings.insert("aa")
strings.insert("bb")
strings.insert("cc")

strings.remove("cc")
strings.remove("dd")

print(strings)
//["bb","cc","aa"]
//순서가 안맞다. 
//set의 가장 큰 특징은 순서가 없고 쭉 나열되어 있다.
//순서는 언제나 시스템적으로 바뀔 수 있기 때문에 순서는 정해져 있지 않다.
//set을 쓰는 가장 큰 이유는 집합의 형태이다.

strings1.insert("aa")
strings1.insert("bb")
strings1.insert("cc")
strings1.insert("zz")

strings2.insert("가")
strings2.insert("나")
strings2.insert("다")
strings2.insert("zz")

//1.union
let union = strings1.union(strings2)
//총 7개 zz는 같기때문에 하나로 본다. 
//set은 똑같은 값을 계속 insert할 수 없다.

//2.intersection
let inter = strings1.intersection(strings2)
//중복되는 값만 출력

//3.symmetricDifference
let symm = strings1.symmetricDifferenct(strings2)
//교집합을 제외한 나머지

//4.subtracting
let sub = strings1.subtracting(strings2)
print(sub)
//차집합 strings1이 가지고 있는거에서 strings2와의 교집합을 뺀다.
  • Dictionary

Key : Value

var sports = [String: Any]()

sports["soccer"] = "korea"
sports["baseball"] = 3
sports["football"] = true


print(sports)
print(sports["soccer"])
//optional 되어있는 상태 unwrapping이 필요하다.
//!를 해주거나 nil 값인지 체크해주는 과정 필요

//1. 
print(sports["soccer"]!)

//2. 
if let hasSoccer = sports["soccer"]{
	print(hasSoccer)
}else {
	print("nil")
}

sports.count

key는 중복이 안된다. 중복되어 있는 형태로 값을 입력하면 최종적으로 입력한 값만 입력된다. 역시나 순서가 없는 type. Array만 순서를 가진다.

Reference

인프런 강의

Tags: ,

Categories:

Updated:

Leave a comment