Skip to content

Instantly share code, notes, and snippets.

@below
Created March 23, 2015 20:36
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save below/e57cfb9323a5ef360e93 to your computer and use it in GitHub Desktop.
Save below/e57cfb9323a5ef360e93 to your computer and use it in GitHub Desktop.
No longer working in Swift 1.2
// In Swift 1.1, I can use "let sideshow : Sideshow!". In Swift 1.2 it has to be a var
// Is this due to the change:
// "In an initializer, constant properties can now only assign a value once." ?
class Main {
var name : String
let sideshow : ImplicitlyUnwrappedOptional<Sideshow>
init (name : String, referenceName : String) {
self.name = name
self.sideshow = Sideshow(name: referenceName, ref: self)
}
}
/* Errors:
main.swift:16:25: error: 'self' used before all stored properties are initialized
self.sideshow = Sideshow(name: referenceName, ref: self)
^
main.swift:13:9: note: 'self.sideshow' not initialized
let sideshow : ImplicitlyUnwrappedOptional<Sideshow>
^
main.swift:16:60: error: variable 'self.sideshow' used before being initialized
self.sideshow = Sideshow(name: referenceName, ref: self)
*/
class Sideshow {
let reference : Main
var name : String
init (name: String, ref reference : Main) {
self.name = name
self.reference = reference
}
}
@tinoheth
Copy link

As I understand the docs, it is a kind of chicken and egg problem*:
Sideshow relies on self, which isn't complete without sideshow, so one reference has to be a variable.
That is ugly, but it is much simpler for the compiler to enforce that only complete objects are passed around, instead of checking each use of half-backed objects for possible problems.
Just tried: It is really possible to do multiple assignments of a constant... that is a little bit odd, but as init is a special case, I could live with that.
I guess they sacrificed ease of use for consistency - didn't they introduce

let x: Int
if a {
    x = 1
} else {
    x = 2
}

in the same release?
Maybe the special handling of constants in init was changed because of that.

*Of course, the "chicken and egg"-problem was solved years ago:
Eggs are one of natures oldest inventions and predate chickens by millions of years; so it should be called the "chicken-and-chicken-egg"-problem actually...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment