처음부터 차근차근
Swift 문법 정리 6 본문
extension
extension 기존타입명 {
// 새로운 기능
}
extension : 확장하다.
기존의 기능을 확장한다
즉, extension이란, class,enum, struct, protocol의 기능을 추가하기 위해 사용하는 것이다.
ex)
// Int형에다 새로운 기능을 추가한다
extension Int {
var plus : Int {
return self + 10
}
}
var test : Int = 10
print(test.plus);
//이것도 가능
print(1.plus);
//결과 : 20
//11
Int형변수 or Int형데이터.추가한기능 해서 사용할 수 있다.
접근 제어(access control)
access control(접근 제어) == access modifier(접근 수정자, 액세스 수정자) == access specifiers(액세스 지정자)
access modifier(접근 수정자)란, 접근 가능 정도를 설정하는 키워드이다.
Swift의 access modifier에는 접근 수준 정도가 높은 순서에 따라 5가지가 있다.
- open : 외부 *모듈(mdule)에서도 접근 가능
- public : 외부 모듈에서도 접근 가능(단, 외부 모듈에서는 override 불가능. open은 가능)
- internal : 해당 모듈 안에 있는 모든 것이 접근 가능(Swift defalut access modifier)
- fileprivate : 해당 소스파일 내부에서만 접근 가능
- private : 정의한 블록 내부에서만 접근 가능
* module(모듈) : 코드 배포의 단일 유닛 즉, 앱이나 라이브러리, Framework(UIKit) 같은걸 말한다.
open은 클래스나 재정의 가능한 클래스 멤버에서만 사용 가능하다.
protocol
protocol 프로토콜명{
}
protocol이란, 선언만 된 함수와 프로퍼티들의 집합이다.
자바, C#의 interface라고 생각하면 편하다.
class는 단일 상속인데 반해, protocol은 다중 상속이 가능하다.
+ 프로토콜이 프로토콜을 상속할 수 있다
protocol 코드 예시)
protocol Flyable {
// get set : 읽기 쓰기 가능
var hour : Int {get set}
// get : 읽기 전용
var minite : Int {get}
func fly()
}
protocol은 함수나 프로퍼티를 반드시 선언만 해야 하며,
protocol에서 프로퍼티를 선언할 때는 꼭 {get set}이나 {get}을 써줘야하고, 꼭 var로 선언해야 한다.
protocol Flyable {
var hour : Int {get set}
var minite : Int {get}
func fly()
}
// Egle 클래스는 Flyable 프로토콜을 채택했다
class Egle : Flyable {
// Flyable protocol을 준수한다
var hour = 4
var minite = 30
func fly() {
print("The eagle flies in the sky for \(hour) hours and \(minite) minutes....")
}
}
// Parrot 클래스는 Flyable 프로토콜을 채택했다
class Parrot : Flyable {
// Flyable protocol을 준수한다
var hour = 1
var minite = 2
func fly() {
print("The parrot flies in the sky for \(hour) hours and \(minite) minutes....")
}
}
let bird1 = Egle()
bird1.fly()
let bird2 = Parrot()
bird2.fly()
// 결과 : The eagle flies in the sky for 4 hours and 30 minutes....
// The parrot flies in the sky for 1 hours and 2 minutes....
프로토콜을 상속받은 것을 프로토콜을 '채택한다(adopt)'라고 한다.
채택한 프로토콜을 구현하는 것을 프로토콜을 '준수한다(conform)'라고 한다.
(영어에서 conform은 '따르다'라는 뜻)
열거형(enum)
열거형(enum)이란, 관련있는 데이터끼리 멤버로 구성되어 있는 자료형이다.
enum PlayerState {
case Wait
case Walk
case Run
case Jump
case Fall
case Roll
}
// 이것도 가능
enum PlayerState {
case Wait, Walk, Run, Jump, Fall, Roll
}
print(PlayerState.Wait)
var player = PlayerState.Run
print(type(of:player), ":", player)
// 두 번째 부터는 열거형명을 생략할 수 있다
player = .Jump
// 이것도 됨
var player : PlayerState
player = .Jump
print(type(of:player), ":", player)
//Wait
//PlayerState : Run
//PlayerState : Jump
열거형명.멤버를 하면 열거형 멤버가 나온다.
그리고, 위에 나와 있지만 이미 열거형이 나와있으면 열거형 명을 생략할 수 있다.
열거형 사용 예제)
enum PlayerState {
case Wait
case Walk
case Run
case Jump
case Fall
case Roll
}
var player : PlayerState
player = .Wait
switch player {
case .Wait:
print("player가 기다리고 있습니다.")
case .Walk:
print("player가 걷고 있습니다.")
case .Run:
print("player가 달리고 있습니다.")
case .Jump:
print("player가 점프하고 있습니다.")
case .Fall:
print("player가 떨어지고 있습니다.")
case .Roll:
print("player가 구르고 있습니다.")
}
//결과 : player가 기다리고 있습니다.
이렇게 열거형과 switch문을 이용해서 코드를 짤 수 있다.
출처 : iOS프로그래밍기초(21-2학기)한성현교수 강의 내용 변형 및 요약
'프로그래밍 > Swift' 카테고리의 다른 글
Mac 사용법과 단축키, Xcode 새 프로젝트 만들기 (0) | 2021.11.01 |
---|---|
Mac과 Window의 차이점 (0) | 2021.10.31 |
Swift 실습 6 (0) | 2021.10.15 |
Swift 문법 정리 5 (0) | 2021.10.08 |
Swift 실습 5 (0) | 2021.10.07 |