3. Swift 기초 - Any, AnyObject, nil, 컬렉션 타입(Array, Dictionary, Set)


Any, AnyObject, nil

  • Any
    Swift의 모든 타입을 지칭하는 키워드로, 데이터 타입의 위치에 들어올 수 있다.
    즉, 모든 타입을 수용할 수 있다는 뜻이다.
var myAny: Any = 100
myAny = "문장도 수용 가능"
//myAny = 123.12 // 컴파일 오류 발생
//double 타입은 할당할 수 없다. (타입 변환에서 다룰 것)




  • AnyObject
    모든 클래스 타입을 지칭하는 프로토콜이다.
    클래스 인스턴스만 읽을 수 있다.
class MyClass{}
var myAnyobject: AnyObject = MyClass()




  • nil
    없음을 의미하는 키워드다. 다른 언어의 NULL, null 등과 유사한 표현이다
    nil을 다루는 자세한 방법은 옵셔널 파트에서 다룰 예정




컬렉션 타입 - Array, Dictionary, Set

컬렉션 타입 : 여러 값들을 묶어서 하나의 변수로 표현할 수 있게함

  • Array
    멤버가 순서를 가진 리스트 형태의 컬렉션 타입
    여러가지 리터럴 문법을 활용할 수 있어 표현법이 다양함
  1. Array 선언 및 생성
 var integers: Array<Int> = Array<Int>()
  var integers: Array<Int> = [Int]()
  //Array<Int> 와 [Int] 는 동일 표현
  var integers: Array<Int> = []
  var integers: [Int] = Array<Int>()
  var integers: [Int] = [Int]()
  var integers: [Int] = []
  var integers = [Int]()

위의 표현 모두 동일하다.



2. Array 활용

//멤버 추가(append)
integers.append(1)
integers.append(100)
// 멤버 포함 여부 확인(contains)
print(integers.contains(100))
// 멤버 교체 : 교체하려는 인덱스에 값을 저장
integers[0] = 99
// 멤버 삭제(remove)
integers.remove(at: 0)
integers.removeLast()
integers.removeAll()
// 멤버 수 확인
print(integers.count)
// 인덱스를 벗어나 접근하려면 익셉션 런타임 오류발생
//integers[0]




3. let을 사용하여 불변 Array 선언

let immutableArray = [1, 2, 3]

수정이 불가능한 Array이므로 멤버를 추가하거나 삭제할 수 없음



  • Dictionary
    '키'와 '값'의 쌍으로 이루어진 컬렉션 타입
    Array와 비슷하게 여러가지 리터럴 문법을 활용할 수 있어 표현 방법이 다양함
  1. Dictionary 선언 및 생성
 // Key가 String 타입이고 Value가 Any인 빈 Dictionary 생성
var myDictionary: Dictionary<String, Any> = [String: Any]()
var myDictionary: Dictionary <String, Any> = Dictionary<String, Any>()
var myDictionary: Dictionary <String, Any> = [:]
var myDictionary: [String: Any] = Dictionary<String, Any>()
var myDictionary: [String: Any] = [String: Any]()
var myDictionary: [String: Any] = [:]
var myDictionary = [String: Any]()

위의 표현 모두 동일하다.



2. Dictionary 활용

// 키에 해당하는 값 할당
myDictionary["someKey"] = "value"
myDictionary["anotherKey"] = 100

print(myDictionary) // ["someKey": "value", "anotherKey": 100]

// 키에 해당하는 값 변경
myDictionary["someKey"] = "dictionary"
print(myDictionary) ["someKey": "dictionary", "anotherKey": 100]

// 키에 해당하는 값 제거
myDictionary.removeValue(forKey: "anotherKey")
myDictionary["someKey"] = nil
print(myDictionary)




3. let을 사용하여 불변 Dictionary 선언

let emptyDictionary: [String: String] = [:]
let initalizedDictionary: [String: String] = ["name": "bonbon", "age": "23"]
// 키에 해당하는 값을 다른 변수나 상수에 할당하고자 할 때는 옵셔널과 타입 캐스팅 파트에서 배울 예정

// "name"이라는 키에 해당하는 값이 없을 수 있으므로 String 타입의 값이 나올 것이라는 보장이 없음
// 컴파일 오류가 발생
// let someValue: String = initalizedDictionary["name"]

수정이 불가능한 Dictionary 이므로 값의 변경이 불가능함



  • Set
    중복되지 않는 멤버가 순서없이 존재하는 컬렉션 (집합)
    Array와 Dictionary랑 다르게 축약형이 존재하지 않음
  1. Set 선언 및 생성
var integerSet: Set<Int> = Set<Int>()




2. Set 활용(1)

// 새로운 멤버 입력(insert)
// 동일한 값은 여러번 insert해도 한번만 저장
integerSet.insert(1)
integerSet.insert(99)
integerSet.insert(99)
integerSet.insert(99)
integerSet.insert(100)

print(intigerSet) // {100, 99, 1}

// 멤버 포함 여부 확인(contains)
print(integerSet.contatins(1))

// 멤버 삭제(remove)
integerSet.remove(99) // {100, 1}
integerSet.removeFirst() // {1}

// 멤버 개수(count)
integerSet.count // 1




3. Set 활용(2)

let setA: Set<Int> = [1, 2, 3, 4, 5]
let setB: Set<Int> = [3, 4, 5, 6, 7]

// 합집합(union)
let union: Set<Int> = setA.union(setB)
print(union) // [2, 4, 5, 6, 7, 3, 1]

// 합집합 오름차순 정렬
let sortedUnion: [Int] = union.sorted()
print(sortedUnion) // [1, 2, 3, 4, 5, 6, 7]

// 교집합(intersection)
let intersection: Set<Int> = setA.intersection(setB)
print(intersection) // [5, 3, 4]

// 차집합(subtracting)
let subtracting: Set<Int> = setA.subtracting(setB)
print(subtracting) // [2, 1]

멤버의 유일성이 보장되기 때문에 집합 연산에 활용하면 유용함






파이썬이랑 조금 비슷한 점이 있는 것 같아서 쉽게 이해할 수 있었다. nil, type casting에 대해서는 뒤에서 배울 예정이니 이번 장에서는 그냥 넘어갔다. 특히, 컬렉션 타입 선언하는 표현 방법이 다양하게 있어서 헷갈리지 않게 주의해야겠다. 다음 장에서는 swift의 함수에 대해 공부할 것이다.

좋은 웹페이지 즐겨찾기