swift2 - How do I write map that works for all types in Swift? -
as exercise, i'm implementing map function takes array , function , applies function elements of array, don't know how declare such works type of array. can like
func intmap(var arr: [int], fun: (int) -> int) -> [int] { in 0 ..< arr.count { arr[i] = fun(arr[i]) } return arr } intmap([1,2,3], {x in return x * x})
but works int.
what type signature swift's built-in map?
edit:
so missing fact can declare param type signatures without declaring types explicitly.
func mymap<t>(var arr: [t], fun: (t) -> t) -> [t] { in 0 ..< arr.count { arr[i] = fun(arr[i]) } return arr } mymap([1,2,3], fun: { x in return x * x })
- create new playground
- just under has
import uikit
typeimport swift
- command click on word swift
this open swift library , can see type definitions there.
and can see:
extension collectiontype { /// return `array` containing results of mapping `transform` /// on `self`. /// /// - complexity: o(n). @warn_unused_result @rethrows public func map<t>(@noescape transform: (self.generator.element) throws -> t) rethrows -> [t]
edited add
alternatively, can write more generalised map
func mymap<t, u>(var arr: [t], fun: t -> u) -> [u] { var a: [u] = [] in 0 ..< arr.count { a.append(fun(arr[i])) } return }
which returns new array, of possibly different type, can see putting in playground.
let = [1, 2, 3] let b = mymap(a, fun: { x in double(x) * 2.1 }) b
Comments
Post a Comment