2

This code doesn't work. It causes a segmentation fault. The entire point of initializing a variable with ! instead of ? is so I can use it with it automatically unwrapping itself. Why is this the case?

var isFoo: Bool!

override func viewDidLoad() {
    super.viewDidLoad()
    isFoo = true
    print(getNumber())
}

func getNumber() -> Int {
    return isFoo ? 1 : 0
}

instead I have to write:

func getNumber() -> Int {
    return isFoo! ? 1 : 0
}

What is most annoying is that the compiler will just give me a Segmentation fault: 11, which has had me debugging for over an hour to conclude that this was where the error was introduced. It doesn't recognize there is anything wrong with the code until I try to compile. Am I missing something?

Sethmr
  • 3,046
  • 1
  • 24
  • 42
  • The compiler should never crash – you should [file a bug report](https://bugs.swift.org). – Hamish Apr 12 '17 at 21:43

2 Answers2

0

A minimal working example.

This gave me now problem:

var isFoo: Bool?

func getNumber() -> Int {
    return isFoo! ? 1 : 0
}

isFoo = true
print(getNumber())

This crashed the compiler with the message While emitting SIL for 'getNumber' (also crashed SourceKit):

var isFoo: Bool!

func getNumber() -> Int {
    return isFoo ? 1 : 0
}

isFoo = true
print(getNumber())

Look like a compiler bug to me. Looks like the bug introduced with this proposal: Abolish ImplicitlyUnwrappedOptional type

Code Different
  • 90,614
  • 16
  • 144
  • 163
-2

I tried this out in a playground and it crashed there too. Funny thing, the Playground actually asked me to file a bug report! Which I will to ...

Now, several months later, I received a response from Apple requesting that I test with the latest XCode 9.3 Beta. I did that and this bug seems to have been fixed.

Bill Waggoner
  • 452
  • 3
  • 11