在Swift 2.2中,我如何简洁地指定一个可能抛出异常的匿名函数
In Swift 2.2, how do I concisely specify an anonymous function that may throw
这是我的代码中的一个精简示例:
struct Widget {
let string: String
init(_ string: String) throws {
self.string = string
}
}
struct Widgets {
let widgets: [Widget]
init(_ strings: [String]) throws {
// Is this really the cleanest way to do the map?
widgets = try strings.map({(string:String) throws -> Widget in
return try Widget(string)
})
}
}
.map
标有 rethrows
关键字,因此您可以
init(_ strings: [String]) throws {
widgets = try strings.map(Widget.init)
}
因为 Widget.init
抛出 .map
也抛出
这是我的代码中的一个精简示例:
struct Widget {
let string: String
init(_ string: String) throws {
self.string = string
}
}
struct Widgets {
let widgets: [Widget]
init(_ strings: [String]) throws {
// Is this really the cleanest way to do the map?
widgets = try strings.map({(string:String) throws -> Widget in
return try Widget(string)
})
}
}
.map
标有 rethrows
关键字,因此您可以
init(_ strings: [String]) throws {
widgets = try strings.map(Widget.init)
}
因为 Widget.init
抛出 .map
也抛出