在初始化器中为struct变量分配闭包

时间:2017-12-14 12:09:52

标签: swift struct closures

我有一个Swift结构,其中两个成员变量是闭包:

struct SettingsItem {
    var title: String = ""
    var textColor: UIColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)
    var selected: () -> Bool = { return false }
    var action: () -> Void = { }
}

当我尝试创建此结构的实例时,出现错误User of unresolved identifier 'selected'。例如:

var settingsItem = SettingsItem(title: "Title", selected = { return true }, action = {})

当我单独分配变量时,它可以工作:

var settingsItem = SettingsItem()
settingsItem.title = ""
settingsItem.selected = { return true }

如何解决此错误?我正在创建一大堆SettingsItem s,因此如果我可以使用初始化程序而不是更详细的选项,那么代码将更加清晰。

3 个答案:

答案 0 :(得分:2)

有两个问题:

  • 参数以selected: ...传递,而不是selected = ...
  • 只有一个默认的成员初始化程序,它采用 all 属性作为参数。

所以这会编译:

var settingsItem = SettingsItem(title: "Title",
                              textColor: #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1),
                              selected: { return true },
                              action: {})

如果使用默认参数值

定义自定义初始值设定项
struct SettingsItem {
    let title: String
    let textColor: UIColor
    let selected: () -> Bool
    let action: () -> Void

    init(title: String,
         textColor: UIColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1),
         selected: @escaping () -> Bool = { return false },
         action: @escaping () -> Void = { })
    {
        self.title = title
        self.textColor = textColor
        self.selected = selected
        self.action = action
    }
}

然后相应的参数是可选的,例如:

let settingsItem = SettingsItem(title: "Title", selected: { return true })

答案 1 :(得分:1)

您已为struct

定义自定义init方法

试试这个

struct SettingsItem {
    var title: String = ""
    var textColor: UIColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)
    var selected: () -> Bool = { return false }
    var action: () -> Void = { }

    init(title: String, textColor: UIColor, selected: @escaping () -> Bool, action: @escaping () -> Void) {
        self.title = title
        self.textColor = textColor
        self.selected = selected
        self.action = action
    }
}

你可以像这样打电话

SettingsItem(title: "title", textColor: .red, selected: { () -> Bool in
        code ...
    }) {
        code ...
}

答案 2 :(得分:0)

以这种方式传递参数应该适合你

var settingsItem = SettingsItem(title: "Title", textColor: UIColor.red, selected: { () -> Bool in
    return true
}) {
    return
}