这段代码会导致 swift 崩溃吗? [英] What about this code causes swift to crash?

查看:42
本文介绍了这段代码会导致 swift 崩溃吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用数组和一个 flatten 函数,以了解 Swift 如何使用泛型.

I'm playing around with arrays and a flatten function in order to wrap my head around how Swift uses generics.

但是,以下代码给出了一个通用的运行操场时出错"弹出窗口,我不知道为什么.

However, the following code gives a generic 'Error running playground' popup, and I can't work out why.

有趣的是,如果我将代码放入项目并尝试编译它,编译器会出现段错误.

Interestingly, if I put the code into a project and try to compile it, the compiler segfaults.

import Cocoa

var arr: [[Int]] = [[1,2], [3,4], [5,6]]

func flatten<S: SequenceType, SS: SequenceType, E where S.Generator.Element == SS, SS.Generator.Element == E>(seq: S) -> [E] {
    var result = [E]()

    for subseq: SS in seq {
        for elem: E in subseq {
            result += [elem]
        }
    }

    return result
}

var flattened = flatten(arr)
println(flattened)

有没有人看到过这样的东西/找到了解决方法?

Has anyone seen something like this / found a workaround?

遗憾的是,我怀疑这可能只是测试版中类型推断的错误 :(

Sadly I suspect this might just be a bug with type inference in the beta :(

推荐答案

这肯定是 Swift 泛型的某种错误(它至少应该显示编译错误而不是明显的崩溃).

This definitely seems to be some sort of bug with Swift generics (it should at least be showing a compile error instead of apparently crashing).

至于解决方法,这似乎有效:

As for a workaround though, this seems to work:

func flatten<E>(seq: [[E]]) -> [E] {
    var result = [E]()

    for subseq: [E] in seq {
        for elem: E in subseq {
            result += [elem]
        }
    }

    return result
}

这篇关于这段代码会导致 swift 崩溃吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆