형변환 : (data) type casting
import UIKit
/*
형변환 : (data) type casting
*/
let intNum: Int = 10
let floatNum: Float = 3.14
let strNum: String = "1234"
// Int -> Double
let doubleNum: Double = Double(intNum)
// Float -> Int
let intNum2: Int = Int(floatNum)
// Int -> String
let strNum2: String = String(intNum)
// String -> Int : 정수모양의 문자만 문자열로 형변환 가능함
// Value of optional type 'Int?' must be unwrapped to a value of type 'Int'
let intNum3: Int? = Int(strNum)
// 가장 안전한 방법이 Optional Binding 임 (if let)
if let newInt = Int(strNum) {
// 형변환 성공: newInt 가 nil 이 아님
print(newInt)
}else{
// 형변환 실패: newInt 가 nil 이 아님
print("형변환 실패")
}
// 클래스의 형변환
// 다형성 : polymorphism <-- 상속 + overriding 이 전제 조건
// 동일한 code 가 실행될 때,
// ( 특정 메소드가 호출될 때 )
// 들어오는 객체가 다르면
// 다른 내용이 실행되는 것
class Animal{
var name: String = ""
func sound(){
print("소리를 냅니다")
}
}
class Dog: Animal{
override func sound(){
print("소리를 냅니다 멍멍 ~~")
}
}
class Cat: Animal{
override func sound(){
print("소리를 냅니다 야옹 ~~")
}
}
class Pig: Animal{
override func sound(){
print("소리를 냅니다 꿀꿀 ~~")
}
}
class Horse: Animal{
override func sound(){
print("소리를 냅니다 히이잉 ~~")
}
}
var animal = Animal()
var dog = Dog()
var cat = Cat()
var pig = Pig()
var horse = Horse()
var animals: [Animal] = []
animals.append(animal)
animals.append(dog)
animals.append(cat)
animals.append(pig)
animals.append(horse)
print("animals: \n \(animals)")
for animal in animals{
animal.sound()
}
/*
is 연산자 : 상속관계인지 아닌지 알아봄
참조변수 is 클래스이름
*/
print(animal is Dog)
print(animal is Animal)
print(dog is Animal)
print(cat is Animal)
print(pig is Animal)
print(horse is Animal)