How do I return a sequence in Swift?

后端 未结 2 534
自闭症患者
自闭症患者 2021-02-03 11:01

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

相关标签:
2条回答
  • 2021-02-03 11:19

    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] }))
        }
    }
    

    Indeed, this works but we had to wrap map result into a helper class which differs from how I do it in C#.

    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:

    1. Associated Types Considered Weird
    2. Associated types vs. type parameters - reason for the former?
    3. Abstract Type Members versus Generic Type Parameters in Scala
    4. Generics and protocols
    0 讨论(0)
  • 2021-02-03 11:27

    I think you are being mislead by the Swift compiler (which is a bit flaky at the moment). The type for your range 0..self.columns is Range<Int>, which is not a Sequence or Collection, so I don't think it can be used via map.

    The implementation works for me:

    extension Matrix {
      func getRow(index: Int) -> T[] {
        var row = T[]()
        for col in 0..self.columns {
          row.append(self[index, col])
        }
        return row
      }
    }
    
    0 讨论(0)
提交回复
热议问题