PKul
PKul

Reputation: 1711

Swift inherited classes

What the different between the following var declared (in Swift)

var taskMgr = TaskManager()

and

var taskMgr:TaskManager = TaskManager()

So far It compiled and worked.

    import UIKit

    var taskMgr = TaskManager()

    struct task{
        var name = "Un-Named"
        var desc = "Un-Desc"
        }

    // Inherited class from NSObject
    class TaskManager: NSObject {
        var tasks = [task]()
        func addTask(name: String, desc: String){
            tasks.append(task(name: name, desc: desc))
        }
    }

Upvotes: 2

Views: 627

Answers (2)

Maxim Shoustin
Maxim Shoustin

Reputation: 77930

If you initiate variable there is no difference between taskMgr and taskMgr:TaskManager. Swift compiler should know about taskMgr type.

However if you define optional variable, you must tell to compiler what type you expected. For example:

var taskMgr:TaskManager?

Or if you want to force type definition to override default type. For example with inherited classes. Consider following:

class ParentClass: NSObject {
    func parentFoo() ->String{
        return "I'm parent method"
    }
}


class ChildClass: ParentClass {
    func childFoo() ->String{
        return "I'm child method"
    }
}

var child = ChildClass() // child has type of ChildClass

println(child.childFoo()) // out: "I'm child method"
println(child.parentFoo())// out: "I'm parent method"

var parentOnly:ParentClass = ChildClass() // <-- force type

println(parentOnly.childFoo()) // ERROR: ParentClass does not have childFoo() method
println(parentOnly.parentFoo()) // out: "I'm parent method"

Upvotes: 1

drewag
drewag

Reputation: 94803

Both version are doing the exact same thing. To understand that, you have to understand that Swift has a feature called Type Inference. This means that the compiler can figure out the type of a variable based on the initial value it is given.

The second version you declared is the full and deliberate version:

var taskMgr:TaskManager = TaskManager()

With this you are creating a variable of type TaskManager and assigning a new task manager to it.

The first version is the shorter version that uses Type Inference:

var taskMgr = TaskManager()

With this you are not explicitly giving taskMgr a type. You don't need to declare the type because you are already assigning it to a value of type TaskManager. The compiler can figure the type out automatically.

You only actually need to specify a type when you need the type to be something different than the compiler will infer from the initial value you are giving it. For example, if you need to make a variable optional or you need a variable to be the type of a superclass of the value you are assigning it.

Upvotes: 1

Related Questions