gpt4 book ai didi

ios - DidSet 在 init 函数 swift 3 中不起作用

转载 作者:行者123 更新时间:2023-11-28 10:11:50 27 4
gpt4 key购买 nike

我已经看过了

Is it possible to allow didSet to be called during initialization in Swift?

对我来说这是行不通的..

我在下面创建类的项目中工作

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) 延迟

use of self in method called $defer before all stored property are initialised

2) 创建将分配该值并从 init 调用它的自定义方法

 private func setCategory(with category:FileCategory) {
self.fileCategory = category
}

Use of method call setCategory before stored property ...

我知道所有存储的属性都应该在创建实例之前初始化。直到那个实例不会被创建所以我不会调用方法(使用自己)可能是为什么上面的解决方案不起作用

有知道的请帮帮我

最佳答案

对我来说,使用 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

关于ios - DidSet 在 init 函数 swift 3 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47072523/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com