Type Casting - 1

박인준·2019년 12월 5일
0

Swift

목록 보기
7/21

Type Check

  • 타입확인 ; type(of:)

예시

type(of: 1)
type(of: 2.0)
type(of: "3")

  • Any : 어떤 타입이든 받아 들일 수 있다.
  • Generic : 타입이 정해져 있는게 아니고 값이 들어올때(사용할 때) 결정이 됨.
func printGenericInfo<T>(_ value: T) {
  let types = type(of: value)
  print("'\(value)' of type '\(types)'")
}
printGenericInfo(1) // 1이 사용되는 순간 타입이 결정됨
printGenericInfo(2.0)
printGenericInfo("3")

  • 타입비교 ; is
  • 타입을 비교할 때 사용
let someAnyArr: [Any] = [1, 2.0, "3"]

for data in someAnyArr {
  if data is Int {
    print("Int type data :", data)
  } else if data is Double {
    print("Double type data : ", data)
  } else {
    print("String type data : ", data)
  }
}

데이터의 타입을 정확히 나눌 필요가 있을때 유용!

상속관계

  • 자식클래스의 타입이 부모클래스의 타입임을 확인하면 반드시 True가 반환됨

예시

class Human {
  var name: String = "name"
}
class Baby: Human {
  var age: Int = 1
}
class Student: Human {
  var school: String = "school"
}
class UniversityStudent: Student {
  var univName: String = "Univ"
}

let student = Student()
student is Human  // 항상 휴먼 ; student는 Human타입 
student is Baby   // false 반환 ; student와 Baby는 형제관계
student is Student // ture 반환 ; 자기 자신타입

let univStudent = UniversityStudent()
student is UniversityStudent // false ; student가 부모이기 때문에 
univStudent is Student // true ; univStudent가 자식클래스이기 때문에

// someArr의 타입은?
let someArr = [Human(), Baby(), UniversityStudent()]
type(of: someArr)
// -> [Human]타입 ; 모두 공통적으로 Human타입을 상속받고 있기 때문에 [Human]타입이 됨

let someArr: Any = [Human(), Baby(), UniversityStudent()] // -> [Any]타입이 됨

@타입을 확인해 보자!

let someArr = [Human(), Baby(), UniversityStudent()]

someArr[0] is Human    // true
someArr[0] is Student  // false
someArr[0] is UniversityStudent  // false
someArr[0] is Baby     // false

someArr[1] is Human    // true
someArr[1] is Student  // false
someArr[1] is UniversityStudent  // false
someArr[1] is Baby     // true

someArr[2] is Human    // true
someArr[2] is Student  // true
someArr[2] is UniversityStudent  // true
someArr[2] is Baby     // false

var human: Human = Student()
type(of: human)
//위의 human타입은 Student타입으로 출력되고 선언은 Human으로 됨

@직접확인한 결과

@출력된 결과

  • 실제론 Student타입이 맞음

@다음은 어떻게 될까?

var james = Student()
james = UniversityStudent() // 정적 - student, 동적 - UniversityStudent

// Q. 다음 중 james 가 접근 가능한 속성은 어떤 것들인가
james.name     // Human 속성 -> 가능
james.age      // Baby 속성  -> 불가능
james.school   // Student 속성 -> 가능
james.univName // UniversityStudent 속성 -> 불가능 ; 컴파일러가 인식하는 타입을 확인해야 함

=> james객체가 univName을 사용하려면 TypeCasting을 이용함

profile
iOS 개발자가 되기 위해

0개의 댓글