[iOS프로그래밍기초(21-2학기)한성현교수님 강의 내용 변형 및 요약]
extension
- class, struct, enum, protocol에 새로운 기능을 추가
- 하위 클래스를 생성하거나 참조하지 않고, 기존 클래스에 메소드, 생성자, 계산 프로퍼티 등의 기능을 추가
extension 기존타입이름 {
// 새로운 기능
}
extension Double {
var volume : Double {
return self * self * self
}
}
let myValue: Double = 4.0
print(myValue.volume) // 64.0
print(3.0.volume) // 27.0
접근 제어(access modifier)
- open : 모듈 외부까지(클래스에만 사용) 접근 가능
- public : 모듈의 모든 소스파일 내에서 접근 가능
- internal : 모듈의 모든 소스 파일 내에서 접근 가능, 해당 모듈 외부의 소스파일에서는 접근 불가
- fileprivate : 해당 소스 파일 내에서만 접근 가능
- private : 동일한 파일에 있는 해당 선언의 extension, 그리고 블록 내에서 접근 가능
프로토콜(protocol)
특정 클래스와 관련없는 함수(메소드)들의 선언 집합( ≒ 자바의 interface)
클래스, 구조체, 열거형, extension에 프로토콜을 채택(adopt) 가능 ↔ 상속은 클래스만 가능
정의
protocol 프로토콜명 {
프로퍼티명
메소드 선언 // 선언만 있음
}
protocol 프로토콜명 : 부모1프로토콜, 부모2프로토콜 {
// 프로토콜은 다중 상속도 가능
}
protocol Operating {
var a : Int { get set }
func operate()
}
class Fan : Operating {
var a : Int = 2
func operate() {
print("약풍")
}
}
let oldfan = Fan()
print(oldfan.a) // 2
oldfan.operate() // 약풍
상속, overloading, overriding, protocal 예제
protocol Operating { // protocol
var phase : Int{ get set }
func operate()
}
class Fan {
var direction : String = "정지"
init(direction: String){ // overloading
self.direction = direction
}
init(){ // overloading
}
func turnon() {
print("\(direction)상태로 On.")
}
}
class NewFan : Fan, Operating { // 상속, 채택(adopt)
var phase : Int = 0 // 준수(conform)
func operate() { // 준수(conform)
phase = phase + 1
}
override func turnon() { // overriding
print("\(direction)상태로 \(phase)단계 On.")
}
}
let newfan1 = NewFan(direction: "회전")
newfan1.operate()
newfan1.turnon() // 회전상태로 1단계 On.
let newfan2 = NewFan()
newfan2.operate()
newfan2.turnon() // 정지상태로 1단계 On.
열거형(enum)
관련있는 데이터들이 멤버로 구성되어 있는 자료형 객체
ex) 빨,주,노,초,파 / 월,화,수,목,금 ...
enum 열거형명 {
// 열거형 정의
}
enum Compass {
case North
case South
case East
case West
}
var direction : Compass
direction = .West
switch direction {
case .North:print("북")
case .South:print("남")
case .East: print("동")
case .West: print("서")
}
* 문맥에서 타입의 추론이 가능한 시점에는 열거형명 생략 가능 ex) direction = .West
'Language > Swift 수업' 카테고리의 다른 글
iOS 프로그래밍 기초 (10) (0) | 2021.11.05 |
---|---|
iOS 프로그래밍 기초 (9) (0) | 2021.11.01 |
iOS 프로그래밍 기초 (6) (0) | 2021.10.09 |
iOS 프로그래밍 기초 (5) (0) | 2021.10.02 |
iOS 프로그래밍 기초 (4) (0) | 2021.09.25 |
Comment