DidSet在init功能中不起作用Swift 3

编程入门 行业动态 更新时间:2024-10-09 10:20:32
本文介绍了DidSet在init功能中不起作用Swift 3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我已经看过

是否可能允许在Swift初始化期间调用didSet?

对我来说,它不起作用.

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

本文发布于:2023-11-28 06:32:06,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1641307.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:中不   功能   DidSet   init   Swift

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!