map function argument type

Here's a little test function:

import UIKit

func foo() {
    let views1 = (1...2).map { _ in
        let v = UIView()
        return v
    }
    
    let views2 = (1...2).map { _ in
        return UIView()
    }
    
    
}


I would expect the two map calls to behave identically. In fact, view2 compiles fine; but I get this error on view1:

error: cannot invoke 'map' with an argument list of type '(@noescape (Int) throws -> _)'
let views1 = (1...2).map { _ in
                             ^
note: expected an argument list of type '(@noescape (Self.Generator.Element) throws -> T)'
let views1 = (1...2).map { _ in
                             ^


Can anyone tell me what is going on?


Thanks.

Replies

import UIKit

func foo() {

let views1: [UIView] = (1...2).map { _ in

let v = UIView()

return v

}


let views2 = (1...2).map { _ in

return UIView()

}


}


it's ok after setting view1 type explicitly, I guess the Swift compiler can't infer view1 type when you write codes like this: define a varible, then return it.

Just FYI, Neil Faiman posted the same question to swift-users and got a bunch of interesting answers. The question is here and you can see the answers here (when you get there, keep clicking Next message to see more follow-up posts).

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"