[英]DidSet not working in init function swift 3
我已經看過
對我來說這是行不通的。
我正在下面創建課程的項目中工作
protocol FileManagerHelper {
var fileName:String {get}
var fileCategory:FileCategory {get set}
var isFileExitsAtPath:Bool {get}
var filePath:String {get}
var fileType:FileTypes {get set}
}
class FileManager:FileManagerHelper {
// Other property
//STORED PROPERY INIT WHEN OBJECT WILL CREATED WITH FileCategory OBJECT
var fileCategory:FileCategory {
didSet {
switch fileCategory {
case .XYZ:
print("Test")
... other cases
}
}
required init(fileCategory:FileCategory,fileType:FileTypes = .Image) {
self.fileCategory = fileCategory
self.path = self.folderPath + self.fileName
}
}
設置方法沒有調用fileCategory
注意:我不想提供默認值,我想從init
方法傳遞它的運行時
嘗試
1) defer
在初始化所有存儲的屬性之前使用稱為$ defer的self in方法
2)創建將分配該值並從init調用它的自定義方法
private func setCategory(with category:FileCategory) {
self.fileCategory = category
}
在存儲屬性之前使用方法調用setCategory ...
我知道所有存儲的屬性都應在實例創建之前初始化。 直到該實例將不會被創建,所以我不會調用方法(使用self)可能就是上述解決方案不起作用的原因
如果有人知道請幫助我
對我來說,使用defer
更容易閱讀。
import Foundation
class A {
var b: String {
didSet {
print("didSet called with value: \(b)")
}
}
init(x: String) {
self.b = x
defer { self.b = x }
}
}
let a = A(x: "It's Working!") // didSet called with value: It's Working!
print(a.b) // It's Working
解決此問題的一種方法是將didSet
邏輯提取到一個單獨的方法中,並從didSet
和init
調用此方法:
class FileManager: FileManagerHelper {
var fileCategory:FileCategory {
didSet {
didSetFileCategory()
}
}
required init(fileCategory:FileCategory,fileType:FileTypes = .Image) {
self.fileCategory = fileCategory
self.path = self.folderPath + self.fileName
didSetFileCategory()
}
private func didSetFileCategory() {
switch fileCategory {
case .XYZ:
print("Test")
//... other cases
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.