class or structure in single file like JAVA. in swift classes and structure are almost same.
If you define class or structure then external interface to that class or structure is automatically available to external developer.
Comparing Classes and Structuress
- can have properties to store value
- can have methods
- can define subscript to access their values using subscript index.
- can have intializers to set up initial values.
- can be extended (extension like category of obj-c)
-can conform to protocols
classes have below part but structure do not have it:
- Inheritance
- runtime type checking of object
- deinitializer like dealloc or destructor
- ref counting allows more than one ref count to class instance
Structure are Value Types and Classes are reference type.
A value type is a type whose value is copied when it is assigned to a variable or constant, or when it is passed to a function. It got new memory and in that memory values gets copied.
reference type because they are not copied when they are assigned to var or const . increasing the reference count.
Ex:( Resolution is structure)
let hd = Resolution(width: 1920, height: 1080)
var cinema = hd
completely different instances behind the scenes. (In short its not like address assigning , its like only copying the values.)
Syntax:
class SomeClass {
// class definition goes here
}
struct SomeStructure {
// structure definition goes here
}
Structures and classes both use initializer syntax for new instances. With () initializer properties initialized to default values.
All structure have automatically generated memberwise initializer.
integers, floating-point numbers, Booleans, strings, arrays and dictionaries—are value types, (i.e structure behind the scene).
Identity Operators
If want to find if two instances refer to same instances of class. To do this swift provided 1.identical to (=== ) and 2. not identical to ( !== ) operators.
Difference between equal to and identical to
1.“Identical to” means that two constants or variables of class type refer to exactly the same class instance.(i.e.same instance of class)
2.“Equal to” means that two instances are considered “equal” or “equivalent” in value, for some appropriate meaning of “equal”, as defined by the type’s designer. Developer write definition for same.
Choosing Between Classes and Structures
Structure instances are always passed by value, and class instances are always passed by reference.
consider creating a structure when one or more of these conditions apply:
- structure is to encapsulate the relatively simple data.
- when assign its value gets copied.
String, Array, and Dictionary are implemented as structures. Means they are copied not referenced.
Its big overhead . This is different from NSArray , NSDictionay and NSArray .
Swift manages all value copying to ensure optimal performance, and you should not avoid assignment to try to preempt this optimization.
0 comments:
Post a Comment