How to create generic protocols in Swift? -
i'd create protocol method takes generic input , returns generic value.
this i've tried far, produces syntax error.
use of undeclared identifier t.
what doing wrong?
protocol apimapperprotocol { func mapfromsource(t) -> u } class usermapper: nsobject, apimapperprotocol { func mapfromsource(data: nsdictionary) -> usermodel { var user = usermodel() usermodel var accountsdata:nsarray = data["accounts"] nsarray return user } }
it's little different protocols. @ "associated types" in apple's documentation.
this how use in example
protocol apimapperprotocol { associatedtype t associatedtype u func mapfromsource(t) -> u } class usermapper: nsobject, apimapperprotocol { typealias t = nsdictionary typealias u = usermodel func mapfromsource(data:nsdictionary) -> usermodel { var user = usermodel() var accountsdata:nsarray = data["accounts"] nsarray // swift 1.2, need line instead // var accountsdata:nsarray = data["accounts"] as! nsarray return user } }
Comments
Post a Comment