Swift编程语言中的树

时间:2014-06-10 09:22:15

标签: tree swift

我尝试用功能方式使用swift创建一棵树

这是我的代码:

//this code works
struct testArbre {
    var racine: Int?
}

let a0 = testArbre(racine:nil)



//this code stuck on error
struct arbre {
    var racine: Int?
        var feuilleGauche: arbre?
        var feuilleDroite : arbre?
}

let a1 = arbre(racine: 10, feuilleGauche: nil, feuilleDroite: nil)

let a2 = arbre(racine:5, feuilleGauche:nil, feuilleDroite:nil)

let a3 = arbre(racine:1, feuilleGauche: a1, feuilleDroite: a2);

这是运行此代码时的错误:

<unknown>:0: error: unable to execute command: Segmentation fault: 11
<unknown>:0: error: swift frontend command failed due to signal (use -v to see invocation)
Command /Applications/Xcode6-Beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swift failed with exit code 254

1 个答案:

答案 0 :(得分:0)

结构是值类型。想象一下如何初始化结构:你有一个struct arbre,所以系统会为它的成员分配内存,这是一个Int和一个struct arbre,所以系统会为它的成员分配内存(一个int和一个struct arbre) ,因此系统将为其成员分配内存(int和struct arbre)。 。 。 - &GT;碰撞

你需要把它变成一个类。

如果你想要一个包含对同一类型的引用的结构,可以用C中的指针轻松完成。

Why does "typdef struct { struct S *s; } S;" containing a pointer to same type compile?