2

I have an enum called Foo in type of String.

I have a struct called MyStruct, which has an optional Foo instance that I want it to be nil initially.

Also MyStruct has a failable initializer.

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."

There is no problem when I rename MyStruct as MyClass and change its type as class.

Is there anyone can tell me why I cannot use both failable initializer and optional enum initialized as nil in a struct?

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 Answer 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):

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I tried your code but I am still getting the same error. It is only compiled when I make it non failable initializer or when I change the type as class..

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.