How can I extend typed Arrays in Swift? -
how can extend swift's array<t> or t[] type custom functional utils?
browsing around swift's api docs shows array methods extension of t[], e.g:
extension t[] : arraytype { //... init() var count: int { } var capacity: int { } var isempty: bool { } func copy() -> t[] } when copying , pasting same source , trying variations like:
extension t[] : arraytype { func foo(){} } extension t[] { func foo(){} } it fails build error:
nominal type
t[]can't extended
using full type definition fails use of undefined type 't', i.e:
extension array<t> { func foo(){} } and fails array<t : any> , array<string>.
curiously swift lets me extend untyped array with:
extension array { func each(fn: (any) -> ()) { in self { fn(i) } } } which lets me call with:
[1,2,3].each(println) but can't create proper generic type extension type seems lost when flows through method, e.g trying replace swift's built-in filter with:
extension array { func find<t>(fn: (t) -> bool) -> t[] { var = t[]() x in self { let t = x t if fn(t) { += t } } return } } but compiler treats untyped still allows calling extension with:
["a","b","c"].find { $0 > "a" } and when stepped-thru debugger indicates type swift.string it's build error try access string without casting string first, i.e:
["a","b","c"].find { ($0 string).compare("a") > 0 } does know what's proper way create typed extension method acts built-in extensions?
for extending typed arrays classes, below works me (swift 2.2). example, sorting typed array:
class highscoreentry { let score:int } extension array element:highscoreentry { func sort() -> [highscoreentry] { return sort { $0.score < $1.score } } } trying struct or typealias give error:
type 'element' constrained non-protocol type 'highscoreentry' update:
to extend typed arrays non-classes use following approach:
typealias highscoreentry = (int) extension sequencetype generator.element == highscoreentry { func sort() -> [highscoreentry] { return sort { $0 < $1 } } } in swift 3 types have been renamed:
extension sequence iterator.element == highscoreentry { // ... }
Comments
Post a Comment