Function 有没有方法引用类型的构造函数?

Function 有没有方法引用类型的构造函数?,function,swift,constructor,Function,Swift,Constructor,在Swift中,您可以引用一个函数,为其赋值,然后在以后使用它。我们都知道这一点。但我想知道我们是否可以用初始化器来实现这一点。下面是一些示例代码。假设我有一个用户结构: struct User { let name: String let age: UInt init(name: String) { self.name = name age = 0 } } 我有一系列的名字 let names = ["Cooper", "Mu

在Swift中,您可以引用一个函数,为其赋值,然后在以后使用它。我们都知道这一点。但我想知道我们是否可以用初始化器来实现这一点。下面是一些示例代码。假设我有一个
用户
结构:

struct User {
    let name: String
    let age: UInt

    init(name: String) {
        self.name = name
        age = 0
    }
}
我有一系列的名字

let names = ["Cooper", "Murph", "Brand", "Dr. Mann"]
我想将这些名称映射到
User
实例。我可以这样做:

let users = map(names, { User(name: $0) })
extension User {
    func getName() -> String { return name }
}

// will be a function that takes a User object,
// and returns a new function that is getName
// called on that object:
let f = User.getName

let u = User("Fred")

// g will be a function that calls getName on u
let g = f(u)
g()  // returns "Fred"

虽然这看起来不错,但我觉得使用
map
函数所采用的闭包是不必要的。我的意思是它基本上取了一个名字并产生
User
。但是我们在
User
struct的构造函数中定义了它。为什么我们要重复?是否有方法将构造函数作为函数获取,并将其直接传递给
map
函数

如果您只是想避免重复,可以通过在参数前面加下划线来跳过指定参数

struct User {
    let name: String
    let age: UInt

    init(_ name: String) {
        self.name = name
        age = 0
    }

    init(_ name: String, _ age : UInt) {
        self.name = name
        self.age = age
    }
}

let names = ["Cooper", "Murph", "Brand", "Dr. Mann"]

let users = map(names, {User($0)})

简短回答:不,不能将
init
作为独立函数引用。不过还是不错的

您可以访问以下成员函数:

let users = map(names, { User(name: $0) })
extension User {
    func getName() -> String { return name }
}

// will be a function that takes a User object,
// and returns a new function that is getName
// called on that object:
let f = User.getName

let u = User("Fred")

// g will be a function that calls getName on u
let g = f(u)
g()  // returns "Fred"
如果
User
是类而不是结构,您也可以这样做:

// h will be equivalent to g above...
let h = u.getName
h()  // returns "Fred"
调用
init
感觉应该更像后者,因为它创建新对象而不是获取现有对象
User.init
应该返回一个函数,该函数取一个名称并返回一个
User
(尽管您有两个初始值设定项,所以需要提供一些类型上下文)。但Swift不允许您这样做(告诉您“没有参数就不能引用初始值设定项”)

不过,有一件有趣的事情是,协议可能需要某些类型的初始值设定项,因此您可以执行以下(相当愚蠢的)操作来伪造初始化任何类型的函数,该函数仅用于娱乐而非实际用途:

protocol StringInitializable {
    init(_ s: String)
}

// no implementation needed as User already conforms
extension User: StringInitializable { }

func initerFromString<T: StringInitializable>(s: String) -> T {
    return T(s)
}

let users: [User] = map(names, initerFromString)

(这实际上用于实际效果的地方是
ExtensibleCollectionType

是否有特殊原因导致
initerFromString
返回闭包,而不是
func initerFromString(name:String)->T{returnt T(name)}
然后
让用户:[User]=map(name,initerFromString)
?不完全是,我猜只是偏好(生成具体函数的泛型函数与泛型函数本身的使用)