Mani murugan
Mani murugan

Reputation: 1802

difference between NSObject and Struct

I want to know the difference between the NSObject and struct..Following example will explain both cases

In struct

struct UserDetails{
    var userName:String
    var userID:String
    var userAge:String
    func userDescription()->String{
        return "name " + userName + "age " + userAge
    }
}

In NSObject Class

class UserDetails: NSObject {
    var userName:String?
    var userID:String?
    var userAge:String?
    func userDescription()->String{
        return "name " + userName! + "age " + userAge!
    }
}

Can you anyone please tell me where I have to use NSObject class, where I have to use struct..?

Upvotes: 7

Views: 3948

Answers (2)

Nate Cook
Nate Cook

Reputation: 93276

Classes and structs in Swift are much closer than in many languages. Both can have properties, method, initializers, subscripts, can conform to protocols, and can be extended. However, only classes can take advantage of inheritance and use deinitializers, and because classes are used by reference, you can have more than one reference to a particular instance.

Structs are used throughout Swift -- arrays, dictionaries, everything optional, and more are built on the struct type, so performance should be very high. You can use struct whenever you don't need the inheritance or multiple references that classes provide.

Upvotes: 5

Grimxn
Grimxn

Reputation: 22487

1) Structs are passed by value, Class instances by reference 2) Classes can be subclassed, Structs can't.

Whether or not the Class is a subclass of NSObject is (mostly) irrelevant. You could equally have said:

class UserDetails {
    var userName:String?
    var userID:String?
    var userAge:String?
    func userDescription()->String{
        return "name " + userName! + "age " + userAge!
    }
}

Upvotes: 6

Related Questions