Array
- 순서가 있는 리스트 컬렉션으로 배열 자료구조이다.
.append(s)
로 배열 끝에 원소를 추가할 수 있다.
.contains(s)
로 배열에 원소 s가 존재하는지 확인할 수 있으며, true/false를 리턴한다.
insert(element,at:index)
로 배열에 원소를 삽입하고 값을 반환한다.
.remove(at:index)
로 배열에 원소를 삭제하고 값을 반환한다.
.removeAll()
로 배열에 있는 모든 원소를 삭제할 수 있다.
.removeLast()
로 배열 마지막에 있는 원소를 삭제하고 값을 반환한다.
.count
프로퍼티로 배열 원소 개수를 얻을 수 있다.
.isEmpty
프로퍼티로 배열이 비어있는지 안비어 있는지 확인할 수 있다.
- 배열 생성시
Array<타입명>
과 [타입명]
은 동일한 표현이다.
- 배열의 인덱스와 값이 모두 필요한 반복문에서는
enumerated()
메소드를 사용한다
.sorted()
메소드를 통해 정렬할 수 있다.
import Swift
var doubles : Array<Double> = Array<Double>()
var doubles2 : Array<Double> = []
var double3 : [Double] = []
var double4 : [Double] = [Double]()
var stringArray = ["hello","hi"]
let immutableArray = [1,2,3]
immutableArray.append(0)
immutableArray.remove(at: 0)
immutableArray.removeAll()
var array1 : ["hel", "lo"]
var array2 : ["wor", "ld!"]
array1 += array2
array1[0...1] = ["aaa","bbb] // ["aaa","bbb","wor","ld!"]
array1 = []
var temp = ["00","11","22","33","44","55","66"]
for (index,value) in temp.enumerated(){
print("\(index) index is \(value)")
}
Dictionary
- 순서가 없는 컬렉션으로 key와 value로 이루어진 HashMap과 비슷하다.
- key를 입력받아 그 key에 해당하는 value를 삭제할 수 있다.
removeValue(forKey : xxx)
를 통해 키가 xxx인 value를 삭제가능하다.
nil
키워드를 통해 삭제와 동일한 연산을 수행할 수 있다.
[:]
로 빈 Dictionary를 선언할 수 있다.
import Swift
var anyDictionary : Dictionary<String,Any> = [String:Any]()
anyDictionary["someKey"] = "value"
anyDictionary["anotherKey"] = 123
anyDictionary.removeValue(forKey : "someKey")
anyDictionary["someKey"] = nil
let emptyDictionary : [String:String] = [:]
let initializedDictionary : [String : String] = ["name" : "lee", "gender" : "male"]
let someValue : String = initializedDictionary["name"]
Set
- 순서가 없는 자료구조이다.
- set에 저장되기 위해서는 hashable 형태여야 하며 Int, String, Double, Float, Bool는 hasable이다.
.insert(x)
를 통해 Set에 넣을 수 있다. 이 떄 중복되는 값이 없었다면 true를, 있었다면 false를 반환한다.
.contains(x)
를 통해 Set에 해당 값이 존재하는지 안하는지 true / false로 반환한다.
.remove(x)
를 통해 해당 하는 값을 삭제하고 그 값을 반환한다.
.removeFirst()
를 통해 원소 하나를 삭제한다.
.count
프로퍼티 접근을 통해 Set에 존재하는 원소의 개수를 알 수 있다.
.union(setx)
를 통해 합집합을 반환할 수 있다.
.sorted()
를 통해 오름차순의 Array를 반환한다.
.intersection(Setx)
를 통해 교집합을 반환할 수 있다.
.subtraction(Setx)
를 통해 차집합을 반환할 수 있다.
.isSubset(of:Setx)
를 통해 자식 집합인지 알 수 있다.
.isSuperset(of:Setx)
를 통해 부모 집합인지 알 수 있다.
.isDisjoint(with:Setx)
를 통해 교집합이 없는지 알 수 있다.
let setEx : Set = ["aa","bb","cc"]
let setA : Set<Int> = [1,2,3]
let setB : Set<Int> = [3,4,5]
let union : Set<Int> = setA.union(setB)
let sortedUnion : [String] = union.sorted()
let intersection : Set<Int> = setA.intersection(setB)
let subtraction : Set<Int> = setA.subtraction(setB)