简体   繁体   中英

How to create PushRow function with generic parameter type

Im having different functions for creating PushRow with different types. 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

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 . 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 .

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.

Updated

You can simply conform your Priority struct to both Equatable and 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
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM