Error in Swift class: Property not initialized at super.init call - properties

I have two classes, Shape and Square
class Shape {
var numberOfSides = 0
var name: String
init(name:String) {
self.name = name
}
func simpleDescription() -> String {
return "A shape with \(numberOfSides) sides."
}
}
class Square: Shape {
var sideLength: Double
init(sideLength:Double, name:String) {
super.init(name:name) // Error here
self.sideLength = sideLength
numberOfSides = 4
}
func area () -> Double {
return sideLength * sideLength
}
}
With the implementation above I get the error:
property 'self.sideLength' not initialized at super.init call
super.init(name:name)
Why do I have to set self.sideLength before calling super.init?

Quote from The Swift Programming Language, which answers your question:
“Swift’s compiler performs four helpful safety-checks to make sure
that two-phase initialization is completed without error:”
Safety check 1 “A designated initializer must ensure that all of the
“properties introduced by its class are initialized before it
delegates up to a superclass initializer.”
Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks.
https://itunes.apple.com/us/book/swift-programming-language/id881256329?mt=11

Swift has a very clear, specific sequence of operations that are done in initializers. Let's start with some basic examples and work our way up to a general case.
Let's take an object A. We'll define it as follows.
class A {
var x: Int
init(x: Int) {
self.x = x
}
}
Notice that A does not have a superclass, so it cannot call a super.init() function as it does not exist.
OK, so now let's subclass A with a new class named B.
class B: A {
var y: Int
init(x: Int, y: Int) {
self.y = y
super.init(x: x)
}
}
This is a departure from Objective-C where [super init] would typically be called first before anything else. Not so in Swift. You are responsible for ensuring that your instance variables are in a consistent state before you do anything else, including calling methods (which includes your superclass' initializer).

From the docs
Safety check 1
A designated initializer must ensure that all of the properties
introduced by its class are initialized before it delegates up to a
superclass initializer.
Why do we need a safety check like this?
To answer this lets go though the initialization process in swift.
Two-Phase Initialization
Class initialization in Swift is a two-phase process. In the first
phase, each stored property is assigned an initial value by the class
that introduced it. Once the initial state for every stored property
has been determined, the second phase begins, and each class is given
the opportunity to customize its stored properties further before the
new instance is considered ready for use.
The use of a two-phase initialization process makes initialization
safe, while still giving complete flexibility to each class in a class
hierarchy. Two-phase initialization prevents property values from
being accessed before they are initialized, and prevents property
values from being set to a different value by another initializer
unexpectedly.
So, to make sure the two step initialization process is done as defined above, there are four safety checks, one of them is,
Safety check 1
A designated initializer must ensure that all of the properties
introduced by its class are initialized before it delegates up to a
superclass initializer.
Now, the two phase initialization never talks about order, but this safety check, introduces super.init to be ordered, after the initialization of all the properties.
Safety check 1 might seem irrelevant as,
Two-phase initialization prevents property values from being accessed before they are initialized can be satisfied, without this safety check 1.
Like in this sample
class Shape {
var name: String
var sides : Int
init(sides:Int, named: String) {
self.sides = sides
self.name = named
}
}
class Triangle: Shape {
var hypotenuse: Int
init(hypotenuse:Int) {
super.init(sides: 3, named: "Triangle")
self.hypotenuse = hypotenuse
}
}
Triangle.init has initialized, every property before being used. So Safety check 1 seems irrelevant,
But then there could be another scenario, a little bit complex,
class Shape {
var name: String
var sides : Int
init(sides:Int, named: String) {
self.sides = sides
self.name = named
printShapeDescription()
}
func printShapeDescription() {
print("Shape Name :\(self.name)")
print("Sides :\(self.sides)")
}
}
class Triangle: Shape {
var hypotenuse: Int
init(hypotenuse:Int) {
self.hypotenuse = hypotenuse
super.init(sides: 3, named: "Triangle")
}
override func printShapeDescription() {
super.printShapeDescription()
print("Hypotenuse :\(self.hypotenuse)")
}
}
let triangle = Triangle(hypotenuse: 12)
Output :
Shape Name :Triangle
Sides :3
Hypotenuse :12
Here if we had called the super.init before setting the hypotenuse, the super.init call would then have called the printShapeDescription() and since that has been overridden it would first fallback to Triangle class implementation of printShapeDescription(). The printShapeDescription() of Triangle class access the hypotenuse a non optional property that still has not been initialised. And this is not allowed as Two-phase initialization prevents property values from being accessed before they are initialized
So make sure the Two phase initialization is done as defined, there needs to be a specific order of calling super.init, and that is, after initializing all the properties introduced by self class, thus we need a Safety check 1

The "super.init()" should be called after you initialize all your instance variables.
In Apple's "Intermediate Swift" video (you can find it in Apple Developer video resource page https://developer.apple.com/videos/wwdc/2014/), at about 28:40, it is explicit said that all initializers in super class must be called AFTER you initialize your instance variables.
In Objective-C, it was the reverse. In Swift, since all properties need to be initialized before it's used, we need to initialize properties first. This is meant to prevent a call to overrided function from super class's "init()" method, without initializing properties first.
So the implementation of "Square" should be:
class Square: Shape {
var sideLength: Double
init(sideLength:Double, name:String) {
self.sideLength = sideLength
numberOfSides = 4
super.init(name:name) // Correct position for "super.init()"
}
func area () -> Double {
return sideLength * sideLength
}
}

Sorry for ugly formatting.
Just put a question character after declaration and everything will be ok.
A question tells the compiler that the value is optional.
class Square: Shape {
var sideLength: Double? // <=== like this ..
init(sideLength:Double, name:String) {
super.init(name:name) // Error here
self.sideLength = sideLength
numberOfSides = 4
}
func area () -> Double {
return sideLength * sideLength
}
}
Edit1:
There is a better way to skip this error. According to jmaschad's comment there is no reason to use optional in your case cause optionals are not comfortable in use and You always have to check if optional is not nil before accessing it. So all you have to do is to initialize member after declaration:
class Square: Shape {
var sideLength: Double=Double()
init(sideLength:Double, name:String) {
super.init(name:name)
self.sideLength = sideLength
numberOfSides = 4
}
func area () -> Double {
return sideLength * sideLength
}
}
Edit2:
After two minuses got on this answer I found even better way. If you want class member to be initialized in your constructor you must assign initial value to it inside contructor and before super.init() call. Like this:
class Square: Shape {
var sideLength: Double
init(sideLength:Double, name:String) {
self.sideLength = sideLength // <= before super.init call..
super.init(name:name)
numberOfSides = 4
}
func area () -> Double {
return sideLength * sideLength
}
}
Good luck in learning Swift.

swift enforces you to initialise every member var before it is ever/might ever be used. Since it can't be sure what happens when it is supers turn, it errors out: better safe than sorry

Edward,
You can modify the code in your example like this:
var playerShip:PlayerShip!
var deltaPoint = CGPointZero
init(size: CGSize)
{
super.init(size: size)
playerLayerNode.addChild(playerShip)
}
This is using an implicitly unwrapped optional.
In documentation we can read:
"As with optionals, if you don’t provide an initial value when you
declare an implicitly unwrapped optional variable or property, it’s
value automatically defaults to nil."

Swift will not allow you to initialise super class with out initialising the properties, reverse of Obj C. So you have to initialise all properties before calling "super.init".
Please go to http://blog.scottlogic.com/2014/11/20/swift-initialisation.html.
It gives a nice explanation to your problem.

Add nil to the end of the declaration.
// Must be nil or swift complains
var someProtocol:SomeProtocol? = nil
// Init the view
override init(frame: CGRect)
super.init(frame: frame)
...
This worked for my case, but may not work for yours

its should be this:
init(sideLength:Double, name:String) {
self.sideLength = sideLength
super.init(name:name)
numberOfSides = 4
}
look at this link:
https://swiftgg.gitbook.io/swift/swift-jiao-cheng/14_initialization#two-phase-initialization

You are just initing in the wrong order.
class Shape2 {
var numberOfSides = 0
var name: String
init(name:String) {
self.name = name
}
func simpleDescription() -> String {
return "A shape with \(numberOfSides) sides."
}
}
class Square2: Shape2 {
var sideLength: Double
init(sideLength:Double, name:String) {
self.sideLength = sideLength
super.init(name:name) // It should be behind "self.sideLength = sideLength"
numberOfSides = 4
}
func area () -> Double {
return sideLength * sideLength
}
}

#Janos if you make the property optional, you don't have to initialise it in init. –
This worked for me.

Related

What is the use of open properties in Kotlin?

I have been learning Kotlin and have come across the concept of open properties. Coming from C++, the concept of "open" makes sense, and extending that logic to properties does as well. However, I can't think of any case where an open val/var is actually necessary or useful. I understand when they make sense for interfaces, but not concrete classes. Furthermore, overriding getters/setters makes sense, but not redefining the property with a new backing field. For example, say you have this kind of class structure:
open class Foo {
open var str = "Hello"
}
class Bar : Foo() {
override var str = "world"
init {
println(str)
println(super.str) // Shows that Bar actually contains "hello" and "world"
}
}
To me, it would seem to be a far better design to make Foo take str as a constructor argument, for instance:
open class Foo(var str = "Hello") // Maybe make a secondary constructor
class Bar : Foo("world") // Bar has only 1 string
This is both more concise, and seems to often be a better design. This is also the way it tends to be done in C++, so maybe I just don't see the benefit of the other way. The only possible time I can see overriding a val/var with a new one is if it for some reason needs to use super's value, like in
override val foo = super.foo * 2
Which still seems pretty contrived.
When have you found this useful? Does it allow for greater efficiency or ease of use?
open fields let you re-define getter and setter methods. It's practically pointless if you just return constants. However altering getter / setter behavior has (infinite) potential, so I'll just throw some ideas:
// propagate get/set to parent class
class Bar : Foo() {
override var str
get() = super.str.toUpperCase()
set(value) {
super.str = value
}
}
// creates a backing field for this property
class Bar : Foo() {
override var str = "World"
get() = field.toLowerCase()
// no need to define custom set if we don't need it in this case
// set(value) { field = value }
}
// instead of writing custom get/set, you can also use delegates
class Bar : Foo() {
override var str by Delegates.observable("world"){ prop, old, new ->
println("${prop.name} changed from $old to $new")
}
}

How to use pointer from other classes in swift

I'm immigrating my old ObjectiveC code to swift. In ObjcC had a separate class to handle my Admob activity.
In this class I've created a pointer in the init func, and when changing scene, I could use this pointer to change the location of the ads banner.
#implementation MyAdsSupport
+(id)ShowAds:(My_Ads_Position)posIndex
{
if (_adsBannerPointer == nil)
{
_adsBannerPointer = [[KTFAdsSupport alloc]initAds:posIndex];
}
else
{
[_adsBannerPointer setAdsPosition:posIndex];
}
return _adsBannerPointer;
}
In Swift I created the Admob class, and managed to present ads on screen but when I try to call the pointer from another class it returns always nil.
Here is my Swift Code:
var adsPointer: My_Ads_Support!
func initAds(myView: UIViewController, atPos: My_Ads_Position) -> KTF_Ads_Support {
if adsPointer == nil {
adsPointer = self
adsPointer.ShowAds(myView: myView, atPos: atPos)
}
else
{
print("adsPointer ALIVE")
adsPointer.setAdsPos( atPos: atPos)
}
return self.adsPointer!
}
How can I set a pointer in Swift to be able to reach the ads banner from any scene?
In your Objective-C code you have three methods, the instance methods initAds: and setAdsPosition:, and the class method ShowAds:. The latter uses a variable, presumably declared static, called _adsBannerPointer.
Your Swift code is not the same. It has two methods, the instance methods initAds and setAdsPos, and one variable, the instance variable adsPointer.
In Swift class methods are termed type methods (as they can belong to classes, structs and enumerations) and are indicated by the use of the keyword static, type (class) variables are also indicated with static. So to follow your Objective-C model you need something along the lines of:
static var adsPointer: My_Ads_Support!
// instance init
init(startingPos : My_Ads_Position) { ... }
// instance set position
fun setAdsPos(atPos : My_Ads_Position) { ... }
static func showAds(myView: UIViewController, atPos: My_Ads_Position) -> KTF_Ads_Support { ... }
HTH

Why won't code that initializes a variable interface property in init block compile?

interface A {
var a: Int
}
class AJunior : A {
override var a: Int
init {
a = 3
}
}
It won't compile because
Property must be initialized or be abstract
But it is initialized. I know I can write:
override var a: Int = 3
But why won't the first example compile? My guess would be that it is a bug or an intentional limitation to simplify compiler implementation, but I'm not sure.
I reported this as a bug, but turns out this behavior is by design because:
you could have code in the init block that could observe the property in its uninitialized state

How to declare a property as a function in Swift?

Here is my code:
import Cocoa
class VC1: NSViewController {
let aFunctionVar ()->Void
}
The compiler however tells me: "Class VC1 has no initializers"
According to the swift example in Apple Swift iBook, they did their examplle like so:
var mathFunction: (Int, Int) -> Int = addTwoInts
But in my case, I'm trying to create a property variable. It is not yet known what the variable will be, so i can't set it there. Any help?
Edit - I already know how to make variables optional and lazy when it comes to simple String/Array/Dictionary types etc. But this is a function type property variable. It is meant to hold a function of type ()->Void. Any help on how this can be done?
In objectiveC this can be done by making a block property like this:
#property (nonatomic, copy) void (^aFunctionVar)();
Declare projectLaunchData as an optional var:
import Cocoa
class VC1: NSViewController {
var projectLaunchData: (()->Void)?
}
Then you can assign a value later:
func test() {
print("this works")
}
let myVC = VC1()
// assign the function
myVC.projectLaunchData = test
// Call the function using optional chaining. This will safely do nothing
// if projectLaunchData is nil, and call the function if it has been assigned.
// If the function returns a value, it will then be optional because it was
// called with the optional chaining syntax.
myVC.projectLaunchData?()
If the value will be known after the object is setup, you can use a lazy variable:
class LazyTester {
lazy var someLazyString: String = {
return "So sleepy"
}()
}
var myLazyTester = LazyTester()
myLazyTester.someLazyString
The compiler is giving you that error because you are defining a mandatory stored variable, projectLaunchData, but not giving it a value. If you know the variables value at init time, you can set it at init time.

How can I keep -Xcheckinit from interfering with the deserialization of Scala objects?

When using the -Xcheckinit compiler option and implementing my own readObject method in a serializable class, I can't call any accessor functions on fields declared in the body of my class from the readObject method. Fields declared as constructor arguments are ok. When I do try to access a field declared in the class body, I get a scala.UninitializedFieldError.
That is, the following code fails on println(y) in the readObject method, even after y has been set in the previous line!
#serializable case class XYPointWithRWAndPrint(var x: Int) {
var y = 0
#throws(classOf[java.io.IOException])
private def writeObject(out: java.io.ObjectOutputStream) {
out.writeInt(x)
out.writeInt(y)
}
#throws(classOf[java.io.IOException])
#throws(classOf[ClassNotFoundException])
private def readObject(in: java.io.ObjectInputStream) {
x = in.readInt()
println(x)
y = in.readInt()
println(y)
}
}
Why?
When using the -Xcheckinit compiler option, the compiler creates a bitmap field that it uses to check initialization.
public volatile int bitmap$0;
In the accessors, the compiler checks the bitmap:
public int y(){
if ((this.bitmap$0 & 0x1) != 0){ return this.y; }
throw new UninitializedFieldError("Uninitialized field: Test.scala: 2".toString());
}
In the constructor, the compiler updates the bitmap:
public XYPointWithRW(int x) {
Product.class.$init$(this);
this.y = 0;
this.bitmap$0 |= 1;
}
Note that it doesn't update the bitmap for constructor arguments, only for fields declared in the class body. It does this because it assumes that you will be calling the constructor and that those fields will be initialized immediately.
During deserialization however, the no-arg constructor of the first non-serializable super class is called (Object in this case), instead of the one-arg constructor shown above. Then readObject is called. The constructor above is never called. Therefore, the bitmap is never updated. Calling the accessor would fail anywhere its called, not just in the readObject method.
To work around this, you must update the bitmap manually. I've chosen to do so from the readObject method. I set all of the bits in the bitmap to 1, like so:
getClass.getField("bitmap$0").set(this, -1)
By setting all the bits to 1, it will work for all the fields (up to 32 fields anyway...what happens beyond that is anyones guess).