在Python中,您可以将类的名称作为参数map,以便创建该类的实例:
class Point(object):
def __init__(self, (x, y)):
self.x = x
self.y = y
coords = [(1., 2.), (3., 4.)]
pts = map(Point, coords)
Run Code Online (Sandbox Code Playgroud)
这经常被证明是一个方便的模式,所以我想在Swift中尝试相同的东西.
首先,我们建立了我们的Point课程:
import Cocoa
class Point
{
var x: Float
var y: Float
init(x: Float, y: Float) {
self.x = x
self.y = y
}
}
var pt = Point(x: 1, y: 2) // works fine
Run Code Online (Sandbox Code Playgroud)
但是当我们尝试使用.map创建实例时,我们会收到错误:
let coords: (Float,Float)[] = [(1, 2), (3, 4)]
// (Point).Type is not convertible to '(Float, Float) -> $T3'
var pts = coords.map(Point)
// Initializer cannot be referenced without arguments
var pts = coords.map(Point.init)
Run Code Online (Sandbox Code Playgroud)
对我来说有趣的是,如果我们首先定义一个包装函数,这确实有效:
func wrapper(x: Float, y: Float) -> Point {
return Point(x: x, y: y)
}
// This *is* successful
var ptsWrapped = coords.map(wrapper)
Run Code Online (Sandbox Code Playgroud)
好的,现在我很好奇这是否禁止使用map方法:
extension Point {
func newPointByAdding(x: Float, y: Float) -> Point {
return Point(x: self.x + x, y: self.y + y)
}
}
// This works as expected
var origin = Point(x: 0, y: 0)
var ptsAdded = coords.map(origin.newPointByAdding)
Run Code Online (Sandbox Code Playgroud)
......不,这很好.
我会很自然地承认我还没有花很多时间在swift上,所以我可能会在规范中遗漏一些禁止这个的东西.
是否可以使用map在swift中创建类/结构的新实例?
如果没有,为什么不呢?
init不是func吗?| 归档时间: |
|
| 查看次数: |
230 次 |
| 最近记录: |