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
..?
The root class of most Objective-C class hierarchies, from which subclasses inherit a basic interface to the runtime system and the ability to behave as Objective-C objects.
Structs are value types and that means that every change on them will just modify that value, Classes are reference types and every change in a reference type will modify the value allocated in that place of memory or reference.
In Swift, structs are value types whereas classes are reference types. When you copy a struct, you end up with two unique copies of the data. When you copy a class, you end up with two references to one instance of the data. It's a crucial difference, and it affects your choice between classes or structs.
Difference between Structs and Classes: Struct are value types whereas Classes are reference types. Structs are stored on the stack whereas Classes are stored on the heap. Value types hold their value in memory where they are declared, but a reference type holds a reference to an object in memory.
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!
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With