DidSet在init功能中不起作用Swift 3 [英] DidSet not working in init function swift 3
问题描述
我已经看过
对我来说,它不起作用.
for me it is not working..
我正在下面创建课程的项目中工作
I am working in project where I have created class below
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
方法将其传递给运行时
NOTE: I don't want to give default value , I want to pass it runtime from init
method
尝试
1)defer
在初始化所有存储的属性之前,在$ defer方法中使用self方法
use of self in method called $defer before all stored property are initialised
2)创建自定义方法,该方法将分配该值并从init调用
2) Create custom method that will assign that value and call it from init
private func setCategory(with category:FileCategory) {
self.fileCategory = category
}
在存储属性之前使用方法调用setCategory ...
Use of method call setCategory before stored property ...
我知道所有存储的属性都应在实例创建之前进行初始化.直到该实例不会被创建,所以我不会调用方法(使用self)可能是上述解决方案无法正常工作的原因
I know that all stored property should be initialised before instance created. Till that instance will not been created so i won't call methods (using self) may be that why above solution not working
如果有人有主意请帮助我
Please help me if any one have idea
推荐答案
对我来说,使用defer
更具可读性.
For me, using the defer
is better readable.
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在init功能中不起作用Swift 3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!