I have an enum called Foo in type of String.
我有一个叫Foo的枚举类型的字符串。
I have a struct called MyStruct, which has an optional Foo instance that I want it to be nil initially.
我有一个名为MyStruct的结构体,它有一个可选的Foo实例,我希望它最初是nil。
Also MyStruct has a failable initializer.
MyStruct还有一个可失败的初始化器。
Problem: When I make MyStruct have both failable initializer and optional Foo instance which will be nil initially, my build fails and I get "Segmentation fault: 11."
问题:当我让MyStruct同时具有可失败初始化器和可选Foo实例时,我的构建失败了,我得到了“分割错误:11”。
There is no problem when I rename MyStruct as MyClass and change its type as class.
当我将MyStruct重命名为MyClass并将其类型更改为class时,没有问题。
Is there anyone can tell me why I cannot use both failable initializer and optional enum initialized as nil in a struct?
有人能告诉我为什么我不能在结构中同时使用可失败初始化器和可选枚举作为nil初始化吗?
import Foundation
enum Foo: String {
case Bla = "blabla"
}
public struct MyStruct {
var myEnum: Foo?
public init?() {}
}
var myStruct = MyStruct()
if let myEnum = myStruct?.myEnum {
println("myEnum is not nil => \(myEnum.rawValue)")
} else {
println("myEnum is nil")
}
1 个解决方案
#1
2
The crash is coming from your empty init?()
method. It's a compiler bug, and you should open a radar about it. The problem is that there's no way for this function to actually fail, and Swift doesn't like that. The following will compile for instance (but will still crash if ignoreme
is a Bool):
崩溃来自空的init?()方法。这是一个编译器错误,您应该对此有所了解。问题是这个函数没有办法真正失败,斯威夫特不喜欢这样。例如,下面将编译(但如果ignoreme是Bool,则仍然会崩溃):
var ignoreme = 0
public struct MyStruct {
var myEnum: Foo?
public init?() {
if ignoreme != 0 { return nil }
}
}
Sometimes (but not always) the compiler gets confused when init?()
has no actual failure cases.
有时候(但并不总是),当init?()没有实际的失败情况时,编译器会感到困惑。
#1
2
The crash is coming from your empty init?()
method. It's a compiler bug, and you should open a radar about it. The problem is that there's no way for this function to actually fail, and Swift doesn't like that. The following will compile for instance (but will still crash if ignoreme
is a Bool):
崩溃来自空的init?()方法。这是一个编译器错误,您应该对此有所了解。问题是这个函数没有办法真正失败,斯威夫特不喜欢这样。例如,下面将编译(但如果ignoreme是Bool,则仍然会崩溃):
var ignoreme = 0
public struct MyStruct {
var myEnum: Foo?
public init?() {
if ignoreme != 0 { return nil }
}
}
Sometimes (but not always) the compiler gets confused when init?()
has no actual failure cases.
有时候(但并不总是),当init?()没有实际的失败情况时,编译器会感到困惑。