100 days of swiftui: 11
https://www.hackingwithswift.com/100/swiftui/11
사과를 저장하거나 꺼내서 먹을 수 있는 냉장고를 다음 예시로 설정했다.
struct Refrigerator {
var apples = 0
mutating func storeApples(count: Int) {
apples += count
}
mutating func eatApples(count: Int) -> Bool {
if count > apples {
return false
} else {
apples -= count
return true
}
}
}
var oneRefrigerator = Refrigerator()
oneRefrigerator.storeApples(count: 5)
if oneRefrigerator.eatApples(count: 3) {
print("Now we have \(oneRefrigerator.apples) apples in the refrigerator")
}
결과:
Now we have 2 apples in the refrigerator
그러나 위의 예시는 Refrigerator
의 멤버 변수인 apples
를 직접 값을 입력해서 변경할 수도 있다. 이를 금지하고 메소드를 통해서만 값을 변경하게 설정하려면 access control을 사용하면 된다.
access control의 종류:
1. private: struct 안의 것만 접근 가능함
2. fileprivate: file 안의 것만 접근 가능함
3. public: 누구나 접근 가능함
4. private(set): 누구나 read할 수 있지만, struct 안의 것만 접근 가능함
다시 예시로 돌아오자면, struct의 밖에서 apples
값을 확인하고 싶으나, method인 storeApples
와 eatApples
만 apples
값을 변경하게 하려면 private(set)을 사용하면 된다.
private(set) var apples = 0
(직접 변경 불가능)
❗️private을 사용하는 멤버 변수의 값이 설정되어 있지 않은 경우 initializer를 직접 설정해야 한다. 이때 자동적으로 제공하면 memberwise initializer는 사용할 수 없다.
코드 파일
https://github.com/soaringwave/Ios-studying/commit/c0518154a03611570d9b72c3d3c85867091eaf21
instance를 생성하지 않고도 struct를 활용하는 방법이 있다. 바로 static을 사용하면 된다.
struct House {
static var members: [String] = []
static func addMember(newMember: String) {
members.append(newMember)
}
}
House.addMember(newMember: "a cat")
print(House.members)
결과:
["a cat"]
static property인 members
와 addMember()
는 House
자체에 속한다. 그래서 struct의 멤버 변수를 변화하는 addMember()
는 mutating 키워드를 작성하지 않아도 된다.
코드 파일
https://github.com/soaringwave/Ios-studying/commit/58a736b2c8c6922118457bd68065358a3b2408cc
위처럼 static property로만 struct를 구성할 수도 있지만, non-static property와도 함께 사용할 수도 있다. 이땐 non-static에서 static으로만 접근이 가능하다. 예시로 non-static을 instance라고 생각하고 static을 특정 static 멤버 변수라고 생각하면 이해가 쉽게 된다.
추가 설명
https://www.hackingwithswift.com/quick-start/beginners/static-properties-and-methods
위 링크에서 작자는 static property를 두 가지 경우에 활용한다고 한다.
struct AppData {
static let version = "1.3 beta 2"
static let saveFilename = "settings.json"
static let homeURL = "https://www.hackingwithswift.com"
}
이러면 어디서든 AppData.version 등을 출력해서 정보를 알아낼 수 있다.
struct Employee {
let username: String
let password: String
static let example = Employee(username: "cfederighi", password: "hairforceone")
}
내가 struct를 만들고 이를 활용해보기 위해서는 instance를 만들고 값을 지정하는 과정을 거쳐야 하는데, 위의 경우엔 Employee.example로 간단히 활용할 수 있다.
struct LegoBrick {
static var numberMade = 0
var shape: String
var color: String
init(shape: String, color: String) {
self.shape = shape
self.color = color
LegoBrick.numberMade += 1
}
}
그리고 위처럼 초기화 하면 된다.
아직 특정 범위에서 어떻게 설정하고 활용하는지에 대해서 헷갈려서 퀴즈를 다시 풀면서 감을 잡아야겠다.
퀴즈
https://www.hackingwithswift.com/review/sixty/static-properties-and-methods