英文:
Extension to Array with generic elements with custom initializer
问题
## 免责声明
请注意,这只是一个简化的示例。实际问题稍微复杂,所以我需要一个实际的数组扩展而不是其他解决方案。
我知道
```swift
let mapped: [MyGeneric<Int>] = items.map { .init(someVariable: $0) }
会起作用,但我正在寻找一种编写通用数组扩展的方法,而不是修复这个简化的代码
问题
我正在尝试编写如下的通用数组/集合扩展:
struct MyGeneric<T: Hashable> {
let someVariable: T
}
期望的输出
下面的代码不起作用,因为我缺少Array扩展,但理想情况下,我的输出应该类似于这样:
let items: [Int] = [1, 2, 3, 4, 5]
let mapped: [MyGeneric<Int>] = .init(items)
所以我需要的是:
extension [MyGeneric<Hashable>] {
init(someArray: [some Hashable]) {
self = someArray.map { MyGeneric(someVariable: $0)}
}
}
但当然,这不会编译,因为扩展中的通用参数没有传递到初始化通用参数。我如何将扩展中的类型传递给其中的函数。我能在这个函数中以某种方式使用 Element.Type
并从中提取通用类型吗?或者也许有一种 extension Array where ...
语法,我不太熟悉?
<details>
<summary>英文:</summary>
## Disclaimer
Please note this is only a simplified example. Actual problem is a bit more complex so I need actual Array extension rather than other solution.
I know that
```swift
let mapped: [MyGeneric<Int>] = items.map { .init(someVariable: $0) }
will work, but I'm looking for a way to write generic array extension not fix this simplified code
Problem
I'm trying to write a generic extension to an array/collection as below:
struct MyGeneric<T: Hashable> {
let someVariable: T
}
Expected output
Code below is not working because I'm missing Array extension, but ideally my output would be something like this:
let items: [Int] = [1, 2, 3, 4, 5]
let mapped: [MyGeneric<Int>] = .init(items)
So what I need is:
extension [MyGeneric<Hashable>] {
init(someArray: [some Hashable]) {
self = someArray.map { MyGeneric(someVariable: $0)}
}
}
but of course this is not compiling because generic parameter from extension is not passed to init generic parameter. How can I pass the type from extension to functions in that. Can I use somehow Element.Type
in this one and extract Generic type from there? Or maybe there is an extension Array where ...
syntax that I'm not familiar with?
答案1
得分: 2
受到@MartinR提供的答案启发,我想出了以下解决方案
extension Array {
init<T>(_ array: [T]) where Element == MyGeneric<T> {
self.init(array.map(MyGeneric.init))
}
}
英文:
Inspired by the answer provided by @MartinR I came up with the following solution
extension Array {
init<T>(_ array: [T]) where Element == MyGeneric<T> {
self.init(array.map(MyGeneric.init))
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论