Properties in Swift - Imtiaz211/interviews GitHub Wiki
What is static and final ?
static is the same as class final, final don't allow inheritance and overriding.
Explain the final keyword into the class?
By adding the keyword
finalin front of the method name, we prevent the method from being overridden. If we can replace the final class keyword with a single word,staticgets the same behavior.
What is the difference between open & public access level?
Publicclasses and class members can only be subclassed and overridden within the defining module (target).openclasses and class members can be subclassed and overridden both within and outside the defining module (target).
//module 1 (It is also called target) public func A(){} open func B(){} //module 2 (It is also called target) override func A(){} // error override func B(){} // success
What is the difference between Fileprivate & Private access level?
Fileprivateis accessible within the current file,privateis accessible within the current declaration.
Required?
Apply this modifier to a
designatedorconvenienceinitializer of a class to indicate that every subclass must implement that initializ.
Internal?
Applying this modifier to a declaration to indicate the declaration can be accessed only by code in the
same moduleas the declaration. By default, most declarations are implicitly marked with theinternal access-level modifier.
Unowned?
Unownedvariables are similar toweakvariables in that they provide a way to reference data without having ownership. However, weak variables can become nil – they are effectively optional. In comparison,unownedvariables must never be set to nil once they have been initialized, which means you don't need to worry about unwrapping optionals.
What is Property in objective-C?
Property allows declared variables with specification like
atomic/nonatomic, or retain/assign.
Difference between @property and variable within interface declaration?
@property: Declaring a property generates getters and setters for the instance variable, according to the criteria within the parenthesis.Variables: Defining the variables in the brackets simply declares them instance variables.
What is the “Interface” and “Implementation”?
interfacedeclares the behaviour of class andimplementationdefines the behaviours of class.
Private
limits the scope class variable to the class that declares it.
Protected
limits instance variable scope to declaring and inheriting classes.
Public
Removes restrictions on the scope of instance variables.
What is the use of the “Dynamic” Keyword?
Instructs the
compiler not to generate a warningif it cannot find implementations of accessor methods associated with the properties whose names follow. Access to that member is never inline or de-virtualized by the compiler.
Copy?
Copyis required when the object ismutable. Use this if you need the value of the object as it is at the moment, and you don’t want that value to reflect any changes made by other owners of the object. You will need to release the object when you are finished with it because you are retaining the copy. Use it for creating ashallowcopy of the object.
Retain?
Retainis required when the attribute is a pointer to anobject. Thesetter generated by @synthesizewill retain the object. You will need to release the object when you are finished with it. By usingretainit will increase theretain countand occupy memory in the auto release pool.Retain creates a reference from one object to another and increases theretain count` of the source object.
Retain Cycle?
This is the
statewhentwo objects holdweak references to one another. Since the first object’s reference count cannot be 0 until the second object is released, and the second object’s reference count cannot be 0 until the first objet is released neither object can be released! It is self-evident that it is not possible tocreate retain cycles with value types, as they are passed by value.
Assign?
Assignis somewhat the opposite of copy. When calling thegetterof anassigned property, it returns areference to the actual data. Typically you use this attribute when you have aproperty of primitive type(float, int, bool).Assign creates a reference from one object to anotherwithout increasing the source’sretaining count.Assignis the default and simply perform a variable assignment.
Atomic?
Is
thread-safe, but it isslow.Atomic accessorsin anon-garbagecollected environment (i.e. when using retain/release/auto release) will use alockto ensure that anotherthread doesn'tinterfere with the correct setting/getting of the value.
Nonatomic?
Nonatomicis used formulti-threadingpurposes. If we have set the nonatomic attribute at the time of declaration, then any other thread wanting access to that object can access it and give result in respect tomultithreading.nonatomicis much faster thanatomic. Always use nonatomic unless you have a very specific requirement for atomic.
What is weak?
Weakis similar to strong except that itwon’t increase the reference count by 1. It does not become anownerof that object but just holds a reference to it. If the object’sreferencecount drops to 0, even though you may still be pointing to it here, it will be deallocated from memory. By default automaticallyget and set to nil. We generally use weak forIBOutlets(UIViewController’s childs) and delegate. aweakreference is always declared as a variable.
What is Strong?
Strongis a replacement for theretain attribute,strongproperty will not destroy an object but only once you set the property tonilwill the object getdestroyed. By default allinstance variablesand local variables arestrongpointers. you use strong only if you need to retain the object. We generally use strong forUIViewControllers(UI Items parents).
Why should delegate is weak swift?
The reason that objects
weak retaintheir delegates is toavoid retaincycles. Imagine the following scenario: objectAcreatesBand retains it, then sets itself asB's delegateAis released by its owner, leaving a retain cycle containingAandB. This is actually a very common scenario.
Readonly?
Use it to
disable settingof the property (prevents code from compiling if there’s and infraction). You can change what’s delivered by thegetterby either changing the variable directly via its instance variable, or within the getter method itself.
Deep?
Copiesduplicate everything. Adeep copyof acollectionis two collections with all of the elements in the original collection duplicated.
Shallow?
Copiesduplicate as little as possible. Ashallowcopy of a collection is a copy of the collection structure, not the elements. with a shallow copy, two collections now share the individual elements.
Unsafe_unretained?
Only exists in
ARC. It works like assign inMRC(Manual Retain Count). These properties won't be retained. Ususally you'd want to use such properties for delegates because they don't need an owner which retains them.
What is the default access modifier for the class?
Internal
What is the default access modifier for the member of the class?
Private.
What is the default access modifier for the member of the struct?
Private.
Why used [self weak] and [self unwoned]
Use a
weakreferencewhen the other instance has a shorter lifetime. Use anunowned referencewhen the other instance has the same lifetime or a longer lifetime.
Stored Property?
Storedproperties can be eithervariable stored propertiesorconstant stored properties.
NOTE: This behavior is due to
structures being value types. When an instance of a value type is marked as aconstant, so are all of its properties. The same is not true for classes, which are reference types. If you assign an instance of areference typeto a constant, you can still change that instance variable properties.
Computed Property?
A
computedproperty with agetterbutno setteris known as aread-only computed property. It alwaysreturns a value, and cannot be set to a different value.Classes,structures, andenumerationscan define computed properties, which do not actually store a value. Instead, they provide agetterand an optional setter to retrieve and set other properties and values indirectly.
Protocol is a type. You can use it in many places like:
- As a parameter type or return type in a function, method, or initializer.
- As the type of a constant, variable, or property
- As the type of items in an array, dictionary, or other container. Because protocols are types, begin their names with a capital letter to match the names of other types in Swift (such as Int, String, and Double).
- Delegation is a design pattern that enables a class or structure to hand off (or delegate) some of its responsibilities to an instance of another type.
Protocol Property?
- A
protocoldeclaration onlyspecifies the required property name and type. It doesn’t say anything about whether the property should be a `stored or computed.- A { get set } property
cannot be a constant stored property. It should be acomputed propertyand bothget and setshould be implemented.Stored and computedproperties are usually associated withinstancesof a particular type. However, properties can also be associated with the type itself. Such properties are known as type properties.- Always prefix type property requirements with the
statickeyword when you define them in a protocol.letdeclarations cannot becomputedpropertiesVariadic parametersare allowed. Default values are not allowed.You can implement a protocol initializer requirement on a conforming class as either adesignated initializer or a convenience initializer. In both cases, you must mark the initializer implementation with the requiredmodifier:- If you mark a
protocol instance methodrequirement asmutating, you donot need to write the mutating keywordwhen writing an implementation of that method for a class. Themutating keyword is only used by structures and enumerations.- If a
subclass overridesadesignated initializerfrom asuperclass, and also implements a matching initializer requirement from a protocol, mark the initializer implementation with both the required and override modifiers:Protocolscan havefailable initializers. Afailableinitializer requirement can be satisfied by afailable or nonfailableinitializer on a conforming type. Anonfailable initializer requirementcan be satisfied by anonfailable initializeror an implicitly unwrapped failable initializer.
Note
You define type properties with the static keyword. For computed type properties for class types, you can use the class keyword instead to allow subclasses to override the superclass’s implementation.