扩展具有通用元素和自定义初始化程序的数组

huangapple go评论56阅读模式
英文:

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&lt;Int&gt;] = 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&lt;T: Hashable&gt; {
	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&lt;Int&gt;] = .init(items)

So what I need is:

extension [MyGeneric&lt;Hashable&gt;] {
	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&lt;T&gt;(_ array: [T]) where Element == MyGeneric&lt;T&gt; {
        self.init(array.map(MyGeneric.init))
    }
}
英文:

Inspired by the answer provided by @MartinR I came up with the following solution

extension Array {
    init&lt;T&gt;(_ array: [T]) where Element == MyGeneric&lt;T&gt; {
        self.init(array.map(MyGeneric.init))
    }
}

huangapple
  • 本文由 发表于 2023年2月10日 03:35:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/75403596.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定