[SOLVED]Ch. 21 Generics, Listing 12.6 Runtime Error

Listing 12.6 is throwing a runtime error I am having difficulties debugging.

Code:

func myMap<T,U>(_ items: [T], _ txform: (T) -> (U)) -> [U] {
var result = [U]()
for item in items {
result.append(f(item))
}
return result
}

The error I am stuck at is result.append(f(item)) – error thrown is f is out of scope.
When I remove f there is a type conversion error.

2 Likes

That’s because name f (function name) is not defined in that scope:

func myMap <T,U> (_ items: [T], _ txform: (T) -> (U)) -> [U] {
     var result = [U]()
     for item in items {
         result.append (f (item))
     }
    return result
}

To transform the items, use the name txform, a parameter, instead:

func myMap <T,U> (_ items: [T], _ txform: (T) -> (U)) -> [U] {
     var result = [U]()
     for item in items {
         result.append (txform (item))
     }
    return result
}
6 Likes

So I guess we can confidently assume that this is a typo?

2 Likes