Can you use map to create instances without a wrapper?

后端 未结 3 1433
半阙折子戏
半阙折子戏 2021-01-21 01:56

In Python, you can give the name of a class as an argument to map in order to create instances of that class:

class Point(object):
    def __init__(         


        
相关标签:
3条回答
  • 2021-01-21 02:21

    I think your conclusion is correct: init isn't being treated as a conventional func. You might want to report this as a bug; I'm not sure if this is intended behavior or not.

    BTW, a more concise way to achieve what you want is:

    coords.map{ p => Point(x: p[0], y: p[1]) }
    
    0 讨论(0)
  • 2021-01-21 02:33

    Update for Swift 2:

    Filing bugs works!

    In Swift 2 this is now possible with coords.map(Point.init):


    Old answer:

    • is it because init is not a func?

    Yep. In Swift, a function type "consists of a parameter and return type separated by an arrow (->)", and map is defined as func map<U>(transform: (T) -> U) -> [U], i.e. it takes in a function. In the grammar, "function declaration" and "initializer declaration" are treated separately. The latter doesn't have a return type because it's not really a function, just a block of code used to initialize instances. And if you try to pass Point.init, you'll get the error "Initializer cannot be referenced without arguments".

    File a bug!

    0 讨论(0)
  • 2021-01-21 02:35

    This is now possible in Xcode 7.0 beta 2

    from the release notes

    Initializers can now be referenced like static methods by referring to .init on a static type reference or type object:

      let x = String.init(5)
      let stringType = String.self
      let y = stringType.init(5)
      let oneTwoThree = [1, 2, 3].map(String.init).reduce(“”, combine: +)
    
    0 讨论(0)
提交回复
热议问题