代码之家  ›  专栏  ›  技术社区  ›  colincameron

在初始化器中将闭包分配给结构变量

  •  -1
  • colincameron  · 技术社区  · 8 年前

    我有一个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 因此,如果我可以使用初始值设定项,而不是使用更详细的选项,那么代码将更加简洁。

    3 回复  |  直到 8 年前
        1
  •  2
  •   Martin R    8 年前

    有两个问题:

    • 参数传递为 selected: ... 不 selected = ... .
    • 只有一个默认的memberwise初始值设定项 全部的 属性作为参数。

    因此,这将编译:

    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 })
    
        2
  •  1
  •   AshvinGudaliya    8 年前

    您已经为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 ...
    }
    
        3
  •  0
  •   Prashanth Rajagopalan    8 年前

    以这种方式传递参数应该对您有用

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