gpt4 book ai didi

swift - 将 Range 和 StrideTo 转换为 Sequence 时出现特殊错误

转载 作者:搜寻专家 更新时间:2023-11-01 05:32:32 25 4
gpt4 key购买 nike

以下函数会产生编译器错误:

func iterateColumnsAlongGravity<S: Sequence>(using block: (_ indexes: S) -> ())
where S.Element == Int {

switch gravityDirection {
case .bot:
for i in stride(from: 0, to: w * h, by: h) {
// 'Range<Int>' is not convertible to 'S'
block(i..<(i + h))
}
case .top:
for i in stride(from: 0, to: w * h, by: h) {
// 'ReversedCollection<(Range<Int>)>' is not convertible to 'S'
block((i..<(i + h)).reversed())
}
case .left:
for y in 0..<h {
let indexes = stride(from: y, to: w * h, by: h).reversed()
// '([Int]) -> ()' is not convertible to '(S) -> ()'
block(indexes)
}
case .right:
for y in 0..<h {
// '(StrideTo<Int>) -> ()' is not convertible to '(S) -> ()'
let indexes = stride(from: y, to: w * h, by: h)
block(indexes)
}
}
}

我不明白为什么编译器不转换 Range<Int>S (以及其他类型)同时 Range显然是符合Sequence它的元素是Int .

它更特别,如果我替换block使用具有相似签名的类方法,没有任何错误:

func printIntSequence<S: Sequence>(_ s: S) where S.Element == Int {
for i in s {
print(i)
}
}

func typeConversionTest() {
switch gravityDirection {
case .bot:
for i in stride(from: 0, to: w * h, by: h) {
printIntSequence(i..<(i + h))
}
case .top:
for i in stride(from: 0, to: w * h, by: h) {
printIntSequence((i..<(i + h)).reversed())
}
case .left:
for y in 0..<h {
let indexes = stride(from: y, to: w * h, by: h).reversed()
printIntSequence(indexes)
}
case .right:
for y in 0..<h {
let indexes = stride(from: y, to: w * h, by: h)
printIntSequence(indexes)
}
}
}

iterateColumnsAlongGravity(using:)之间的唯一区别和 typeConversionTest()第一个将 block 作为参数。

最佳答案

期间 the discussion在 Swift 论坛上透露了以下信息:

  1. 我尝试实现的是高阶多态性,这个重要的特性还没有添加到 Swift 中。
  2. 可能最简单的解决方案是放弃泛型并使用 StrideTo<Int>这里。

    func iterateColumnsAlongGravity(using block: (_ indexes: StrideTo<Int>) -> ()) {
    switch gravityDirection {
    case .bot:
    for i in stride(from: 0, to: w * h, by: h) {
    block(stride(from: i, to: i + h, by: 1))
    }
    case .top:
    for i in stride(from: 0, to: w * h, by: h) {
    block(stride(from: i + h - h, to: i - h, by: -1))
    }
    case .left:
    for y in 0..<h {
    block(stride(from: (w - 1) * h + y, to: -1, by: -h))
    }
    case .right:
    for y in 0..<h {
    block(stride(from: y, to: w * h, by: h))
    }
    }
    }

关于swift - 将 Range 和 StrideTo 转换为 Sequence 时出现特殊错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53447496/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com