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
final
in front of the method name, we prevent the method from being overridden. If we can replace the final class keyword with a single word,static
gets the same behavior.
What is the difference between open & public access level?
Public
classes and class members can only be subclassed and overridden within the defining module (target).open
classes 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?
Fileprivate
is accessible within the current file,private
is accessible within the current declaration.
Required?
Apply this modifier to a
designated
orconvenience
initializer 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 module
as the declaration. By default, most declarations are implicitly marked with theinternal access-level modifier
.
Unowned?
Unowned
variables are similar toweak
variables in that they provide a way to reference data without having ownership. However, weak variables can become nil – they are effectively optional. In comparison,unowned
variables 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”?
interface
declares the behaviour of class andimplementation
defines 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 warning
if 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?
Copy
is 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 ashallow
copy of the object.
Retain?
Retain
is required when the attribute is a pointer to anobject
. Thesetter generated by @synthesize
will retain the object. You will need to release the object when you are finished with it. By usingretain
it will increase theretain count
and occupy memory in the auto release pool.Retain creates a reference from one object to another and increases the
retain count` of the source object.
Retain Cycle?
This is the
state
whentwo objects hold
weak 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?
Assign
is somewhat the opposite of copy. When calling thegetter
of 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’s
retaining count.Assign
is the default and simply perform a variable assignment.
Atomic?
Is
thread-safe
, but it isslow
.Atomic accessors
in anon-garbage
collected environment (i.e. when using retain/release/auto release) will use alock
to ensure that anotherthread doesn't
interfere with the correct setting/getting of the value.
Nonatomic?
Nonatomic
is used formulti-threading
purposes. 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
.nonatomic
is much faster thanatomic
. Always use nonatomic unless you have a very specific requirement for atomic.
What is weak?
Weak
is similar to strong except that itwon’t increase the reference count by 1
. It does not become anowner
of that object but just holds a reference to it. If the object’sreference
count 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. aweak
reference is always declared as a variable.
What is Strong?
Strong
is a replacement for theretain attribute
,strong
property will not destroy an object but only once you set the property tonil
will the object getdestroyed
. By default allinstance variables
and local variables arestrong
pointers. 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 retain
their delegates is toavoid retain
cycles. Imagine the following scenario: objectA
createsB
and retains it, then sets itself asB's delegate
A
is released by its owner, leaving a retain cycle containingA
andB
. This is actually a very common scenario.
Readonly?
Use it to
disable setting
of the property (prevents code from compiling if there’s and infraction). You can change what’s delivered by thegetter
by either changing the variable directly via its instance variable, or within the getter method itself.
Deep?
Copies
duplicate everything. Adeep copy
of acollection
is two collections with all of the elements in the original collection duplicated.
Shallow?
Copies
duplicate as little as possible. Ashallow
copy 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
weakreference
when the other instance has a shorter lifetime. Use anunowned reference
when the other instance has the same lifetime or a longer lifetime.
Stored Property?
Stored
properties can be eithervariable stored properties
orconstant 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 type
to a constant, you can still change that instance variable properties.
Computed Property?
A
computed
property with agetter
butno setter
is known as aread-only computed property
. It alwaysreturns a value
, and cannot be set to a different value.Classes
,structures
, andenumerations
can define computed properties, which do not actually store a value. Instead, they provide agetter
and 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
protocol
declaration 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 property
and bothget and set
should be implemented.Stored and computed
properties are usually associated withinstances
of 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
static
keyword when you define them in a protocol.let
declarations cannot becomputed
propertiesVariadic parameters
are 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 method
requirement asmutating
, you donot need to write the mutating keyword
when writing an implementation of that method for a class. Themutating keyword is only used by structures and enumerations
.- If a
subclass overrides
adesignated initializer
from asuperclass
, and also implements a matching initializer requirement from a protocol, mark the initializer implementation with both the required and override modifiers:Protocols
can havefailable initializers
. Afailable
initializer requirement can be satisfied by afailable or nonfailable
initializer on a conforming type. Anonfailable initializer requirement
can be satisfied by anonfailable initializer
or 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.