1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 | import UIKit class Vehicle{ var currentSpeed = 0.0 //stored property var description:String{ //computed property : getter의 역할 return "traveling at \(currentSpeed) miles per hour" } func makeNoise(){ print("noiseless") } } let someVehicle = Vehicle(); //인스턴스 생성 someVehicle.currentSpeed = 1.0 print("Vehicle : \(someVehicle.description)") //Vehicle : traveling at 1.0 miles per hour //상속 class Bicycle:Vehicle{ var hasBasket = false } let bicycle = Bicycle() bicycle.hasBasket = true bicycle.currentSpeed = 15.0 print("Bicycle : \(bicycle.description)") //Bicycle : traveling at 15.0 miles per hour class Tandem:Bicycle{ //*Tandem = 이인용 자전거 var currentNumberOfPassengers = 0 //stored property override var description:String{ //computed property, override - 위에꺼랑 겹쳐서 재정의 return "traveling at \(currentSpeed) miles per hour, number of passenger : \(currentNumberOfPassengers), basket : \(hasBasket)" } } let tandem = Tandem() tandem.hasBasket = true tandem.currentNumberOfPassengers = 2 tandem.currentSpeed = 22.0 print("Tandem : \(tandem.description)") //Tandem : traveling at 22.0 miles per hour, number of passenger : 2, basket : true class Train:Vehicle{ override func makeNoise() { print("Choo Choo") } } let train = Train() train.makeNoise() //Choo Choo class Car:Vehicle{ var gear = 1 override var description:String{ //computed property : getter의 역할 return super.description + " in gear \(gear)" //super = 상위 클래스 } } let car = Car() car.currentSpeed = 25.0 car.gear = 3 print("Car : \(car.description)") //Car : traveling at 25.0 miles per hour in gear 3 //Property Observer : 속성값을 지켜보면서 속성값의 변화에 반응 //- willSet : 값이 저장되기 전에 호출되는 Property Observer //- didSet : 새로운 값이 저장된 후, 바로 호출되는 Property Observer class AutomaticCar:Car{ override var currentSpeed: Double{ didSet{ //값이 설정이 되면 반응 gear = Int(currentSpeed / 10) + 1 } } } let automatic = AutomaticCar() automatic.currentSpeed = 30.0 print("AutomaticCar : \(automatic.description)") //AutomaticCar : traveling at 30.0 miles per hour in gear 4 |
'프로그래밍 > Swift | iOS' 카테고리의 다른 글
[Swift3 & iOS10] optionalValue (0) | 2017.12.02 |
---|---|
[Swift3 & iOS10] struct(구조체) (0) | 2017.12.01 |
[Swift3 & iOS10] function (0) | 2017.12.01 |
[Swift3 & iOS10] 조건문 if,switch (0) | 2017.12.01 |
[Swift3 & iOS10] 반복문 for,while (0) | 2017.11.30 |