[英]How to create PushRow function with generic parameter type
Im having different functions for creating PushRow with different types. 我有不同的功能来创建具有不同类型的PushRow。 it includes both string type and custom defined types also.
它同时包括字符串类型和自定义类型。 How to merge these functions to a single one which accept generic parameter for creating PushRow
如何将这些功能合并为一个接受通用参数以创建PushRow的功能
fileprivate func createPushRow1() {
form +++ Section(label)
<<< PushRow<String>(String(typeId)) {
$0.title = label.lowercased()
$0.selectorTitle = "Pick " + label.lowercased()
$0.options = optionList
}.onChange({ [unowned self] row in
row.value = row.value
})
}
fileprivate func createPushRow2() {
self.form +++ Section(label)
<<< PushRow<Priority>(String(typeId)) {
$0.title = label.lowercased()
$0.selectorTitle = "Pick " + label.lowercased()
$0.options = priorityList
$0.displayValueFor = {
guard let priority = $0 else { return nil }
return priority.name
}
$0.onChange({ [] row in
row.value = row.value
})
}
}
PushRow
options require conformance to Equatable
. PushRow
选项要求符合Equatable
。 So assuming your Priority
class conforms to Equatable
, you can use the follow function which takes a generic equatable type as a parameter to create a PushRow
. 因此,假设您的
Priority
类符合Equatable
,则可以使用follow函数,该函数将通用的equatable类型作为参数来创建PushRow
。
func createPushRow<T: Equatable>(type: T.Type, options: [T]) {
self.form +++ Section(label)
<<< PushRow<T>(String(typeId)) {
$0.title = label.lowercased()
$0.selectorTitle = "Pick " + label.lowercased()
$0.options = options
}
}
You can simply use the function like this. 您可以像这样简单地使用该函数。
self.createPushRow(type: String.self, options: ["option A", "option B"])
However, you need to be careful on your PushRow tag String(typeId)
though, Eureka does not accept rows with the same tag, so you will probably want to pass unique row tag as another parameter in the generic function. 但是,您需要注意PushRow标记的
String(typeId)
,因为Eureka不接受带有相同标记的行,因此您可能希望将唯一的行标记作为通用函数中的另一个参数传递。
Updated 更新
You can simply conform your Priority
struct to both Equatable
and CustomStringConvertible
. 您可以简单地使
Priority
结构符合Equatable
和CustomStringConvertible
。
struct Priority: Equatable, CustomStringConvertible {
let id: Int
let name: String
var description: String {
return self.name
}
static func == (lhs: Priority, rhs: Priority) -> Bool {
return lhs.id == rhs.id
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.