gpt4 book ai didi

swift - 为什么这个闭包没有我期望的参数?

转载 作者:行者123 更新时间:2023-11-28 12:33:01 25 4
gpt4 key购买 nike

我有一个 SettingsViewController 并创建了一个结构来定义每个设置所需的信息。

///Represents a list of the options needed to populate a `SettingsTableViewCell`
public struct Setting {
///The image to use for the icon
var imageName : String

///The text to display as the title of the setting
var title : String

///Called when the switch is tapped. If no closure is supplied, the switch is hidden
var switchCallback: ((_ status: Bool)->())?
}

View Controller 保留这些设置的数组,以便稍后在 TableView 中使用。下面提供了一个示例:

let options : [Setting] =
[
Setting(imageName: "notifications", title: "Bump Notifications") {updateNotificationSetting($0)},
...
]

但是,当我尝试编译时,出现错误:

Cannot convert value of type '(SettingsViewController) -> (Bool) -> ()' to expected argument type '((Bool) -> ())?'

有人可以解释一下 (SettingsViewController) 的来源吗?如果可以的话,请问我需要更改什么来修复它?


对于 SSCCE,请参见下文:

import UIKit

///Represents a list of the options needed to populate a `SettingsTableViewCell`
public struct Setting {
///The image to use for the icon
var imageName : String

///The text to display as the title of the setting
var title : String

///Called when the switch is tapped. If no closure is supplied, the switch is hidden
var switchCallback: ((_ status: Bool)->())?
}



@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?

let options : [Setting] =
[
//Error is on the following line
Setting(imageName: "notifications", title: "Bump Notifications") {isOn in updateSetting(isOn)},
]

func updateSetting(isOn : Bool) {

}

}

最佳答案

Setting 初始化器中的闭包正在捕获 self。但是,Swift中的self只有在对象的所有属性都初始化后,即let options初始化后才可用。

打破循环的一种方法是使用属性的惰性初始化:

public struct Setting {
var imageName : String
var title : String
var switchCallback: ((_ status: Bool)->())?
}

class MyClass {
lazy var options: [Setting] = [
Setting(imageName: "x", title: "X") { [unowned self] in self.updateSetting(isOn: $0)}
]

func updateSetting(isOn : Bool) {}
}

请注意显式类型 : [Setting] 目前是声明所必需的。

请注意,您需要使用 [unowned self][weak self] 来打破发布周期(感谢@rob 的评论)。

关于swift - 为什么这个闭包没有我期望的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41564987/

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