Ios 如何将选择器或函数委托添加为结构的成员?

Ios 如何将选择器或函数委托添加为结构的成员?,ios,swift,Ios,Swift,对于项列表中的每个项我想指定一个函数成员,如let function:???,其类型允许我分配一个函数,如open(item) 但更有效的方法是使用协议: protocol ItemDelegate { func call(item: Item) } struct Item { let label: String let roomID: Int let itemDelegate: ItemDelegate } 第二种解决方案可能存在于堆栈中。它有更高的性能 对

对于
项列表中的每个项
我想指定一个函数成员,如
let function:???
,其类型允许我分配一个函数,如
open(item)

但更有效的方法是使用协议:

protocol ItemDelegate {
    func call(item: Item)
}

struct Item {
    let label: String
    let roomID: Int
    let itemDelegate: ItemDelegate
}
第二种解决方案可能存在于堆栈中。它有更高的性能

对于全局方法,请使用枚举命名空间:

您操场上的问题是tabTwoFunction声明得太晚。要修复它,请将其包装到我的命名空间中:

enum NameSpace {

static func tabTwoFunction(_ item: Item) -> Void {

}

static let tabTwoItems = [
    NameSpace.Item(label: "Label", id: 1234, image: "image", function: tabTwoFunction)
]

struct Item {
    let label: String
    let id: Int
    let image: String
    let function: (Item) -> Void
}
}
但更有效的方法是使用协议:

protocol ItemDelegate {
    func call(item: Item)
}

struct Item {
    let label: String
    let roomID: Int
    let itemDelegate: ItemDelegate
}
第二种解决方案可能存在于堆栈中。它有更高的性能

对于全局方法,请使用枚举命名空间:

您操场上的问题是tabTwoFunction声明得太晚。要修复它,请将其包装到我的命名空间中:

enum NameSpace {

static func tabTwoFunction(_ item: Item) -> Void {

}

static let tabTwoItems = [
    NameSpace.Item(label: "Label", id: 1234, image: "image", function: tabTwoFunction)
]

struct Item {
    let label: String
    let id: Int
    let image: String
    let function: (Item) -> Void
}
}

(输入:String)->(String)
这将使它成为一个接受字符串并返回字符串的函数。
让函数:(Item)->Void
?在
项(标签:“label”)之后是否应该有其他内容,id:1234,图像:
?我更新了我的问题:这些方法不起作用。您的代码中缺少了一点init方法。您如何设置函数?
(输入:字符串)->(字符串)
这将使它成为一个接受字符串并返回字符串的函数。
让函数:(项)->Void
?在
项(标签:“label”,id:1234,图像:
)之后是否应该有其他内容?我更新了我的问题:这些方法不起作用您在代码中遗漏了一点init方法。您如何设置函数?
enum NameSpace {

static func tabTwoFunction(_ item: Item) -> Void {

}

static let tabTwoItems = [
    NameSpace.Item(label: "Label", id: 1234, image: "image", function: tabTwoFunction)
]

struct Item {
    let label: String
    let id: Int
    let image: String
    let function: (Item) -> Void
}
}