如何在Swift中返回序列? [英] How do I return a sequence in Swift?
问题描述
我正在尝试为本书中的Matrix
示例编写扩展,稍作调整,使其具有通用性 .
我正在尝试编写一种名为getRow
的方法,该方法在给定的行中返回一个值序列.
I'm trying to write an extension for the Matrix
example from the book, slightly tweaked to be generic.
I'm trying to write a method called getRow
that returns a sequence of values at the given row.
在C#中,我会这样写:
In C#, I would have written this:
IEnumerable<T> GetRow (int row)
{
return Enumerable
.Range (0, this.columns)
.Select ((column) => this.grid[row, columns]);
}
或者
IEnumerable<T> GetRow (int row)
{
for (var column = 0; column < this.columns; column++) {
yield return this.grid[row, column];
}
}
我不确定如何在Swift中执行此操作.
I'm not sure how to do this in Swift though.
Sequence
似乎等同于IEnumerable<T>
,但我不明白为什么它使用typealias
而不是仅仅定义为Sequence<T>
(
Sequence
seems to be the equivalent to IEnumerable<T>
but I don't understand why it uses typealias
instead of just being defined as Sequence<T>
(see also this). Defining a method that returns generic Sequence<T>
did not work:
extension Matrix {
// Cannot specialize non-generic type 'Sequence'
func getRow<T>(index: Int) -> Sequence<T> {
return map(0..self.columns, { self[index, $0] })
}
}
然后我摆脱了<T>
(但是它应该是通用的吗?):
Then I got rid of <T>
(but how is it supposed to be generic?):
extension Matrix {
func getRow(index: Int) -> Sequence {
return map(0..self.columns, { self[index, $0] })
}
}
此编译!但是我不能使用它:
This compiles! However I can't use it:
var row = grid.getRow(0)
// 'Sequence' does not conform to protocol '_Sequence_'
for i in row {
println("\(i)")
}
如何正确键入map
结果,以便可以在for..in
循环中使用它?
How do I properly type map
result so it can be consumed in a for..in
loop?
有关此问题的更多信息:被视为怪异的关联类型
More on this issue: Associated Type Considered Weird
推荐答案
Joe Groff 建议包装结果在SequenceOf<T>
中:
Joe Groff suggested to wrap the result in SequenceOf<T>
:
extension Matrix {
func getRow(index: Int) -> SequenceOf<T> {
return SequenceOf(map(0..self.columns, { self[index, $0] }))
}
}
确实可以,但是我们不得不将map
结果包装到一个帮助程序类中,该类与我在C#中的用法不同.
Indeed, this works but we had to wrap map
result into a helper class which differs from how I do it in C#.
我必须承认我还不明白为什么Sequence
和Generator
使用typealias
并且不是通用协议(例如C#中的IEnumerable<T>
).正在进行有关此区别的有趣讨论,因此我会留出一些链接以示好奇:
I have to admit I don't yet understand why Sequence
and Generator
use typealias
and aren't generic protocols (like IEnumerable<T>
in C#). There is an interesting ongoing discussion about this distinction so I'll leave a few links for a curious mind:
- Associated Types Considered Weird
- Associated types vs. type parameters - reason for the former?
- Abstract Type Members versus Generic Type Parameters in Scala
- Generics and protocols
这篇关于如何在Swift中返回序列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!