Property vs. Method
Computed property는 struct, class 내의 stored property를 가공하여 사용하는 property이다. 어쩌면 그 쓰임이 메소드와 비슷하다. 그렇다면 왜 메소드를 사용하지 않고 굳이 computed propery를 쓰는 걸까?
우선 Property는 호출시 (저장된) 값을 하나 반환한다.
반면 Method는 호출시 어떤 작업을 한다.
만약 메소드가 값을 하나 반환하는 작업을 한다면 computed property와 메소드 중 어떤 것을 어떤 기준으로 사용해야할까?
다음 기준으로 computed property와 method를 구분하여 사용할 수 있다.
Method
Struct 내에도 메소드를 정의할 수 있다고 했다. 이때 메소드가 Struct의 stored property를 변형시키는 작업을 한다면, func 키워드 앞에 mutating을 붙여야 한다.
struct Lecture{
var title: String
var maxStudent: Int = 10
var numOfRegistered: Int = 0
func remainSeats() -> Int {
let remainSeats = maxStudent - numOfRegistered
return remainSeats
}
mutating func register() {
if numOfRegistered < maxStudent {
numOfRegistered += 1 // Stored properety를 변형시키므로 func 앞에 mutating을 붙인다.
}
}
}
타입 프로퍼티처럼, 타입 메소드도 정의할 수 있다. 마찬가지로 static 키워드를 이용하여 정의한다. 타입 메소드도 Struct/Class 타입 자체의 기능을 정의하고 싶을 때 사용한다.
struct Lecture{
var title: String
var maxStudent: Int = 10
var numOfRegistered: Int = 0
func remainSeats() -> Int {
let remainSeats = maxStudent - numOfRegistered
return remainSeats
}
mutating func register() {
if numOfRegistered < maxStudent {
numOfRegistered += 1
}
}
static let target: String = "Anybody want to learn something"
static func 소속학원이름() -> String {
return "패캠"
}
}
Lecture.소속학원이름() // "패캠"
패스트캠퍼스 [직장인 실무교육]
프로그래밍, 영상편집, UX/UI, 마케팅, 데이터 분석, 엑셀강의, The RED, 국비지원, 기업교육, 서비스 제공.
fastcampus.co.kr
본 포스팅은 패스트캠퍼스 환급 챌린지 참여를 위해 작성되었습니다.
'iOS > iOS 앱 개발 올인원 패키지 Online' 카테고리의 다른 글
[iOS] 패스트캠퍼스 챌린지 21일차 - Class(1) (0) | 2021.09.26 |
---|---|
[iOS] 패스트캠퍼스 챌린지 20일차 - Structure(5). Extension (0) | 2021.09.25 |
[iOS] 패스트캠퍼스 챌린지 18일차 - Structure(3) (0) | 2021.09.23 |
[iOS] 패스트캠퍼스 챌린지 17일차 - Structure(2).예제 (0) | 2021.09.22 |
[iOS] 패스트캠퍼스 챌린지 16일차 - Structure(1). Structure vs. Class (0) | 2021.09.21 |