Enumeration - Imtiaz211/interviews GitHub Wiki
What is a singleton?
- The
singletonis a software design pattern thatrestricts the instantiationof aclass to one object. This is useful when exactly one object is needed to coordinate actions across the system.- A
singletonclass returns thesame instanceno matter how many times an application requests it.- It usually uses lazy loading to create the single instance when it’s needed the first time.
- Singleton Objects stored on heap while static class stored in stack.
- Singleton Objects can have constructor while Static Class cannot.
- Singleton Objects can dispose but not static classes.
- Singleton Objects can clone but not with static class.
Disadvantage of Singleton
- Unit testing is more difficult (because it introduces a global state into an application).
- This pattern reduces the potential for parallelism within a program, because to access the singleton in a multi-threaded system, an object must be serialized (by locking)
What is the difference between strut and classes?
- Classes - classes are reference types, - they increase their reference count when passed to a function or assigned to a variable or constant. - They also have some extra stuff like inheritance from a superclass, type casting, and deinitializers.
- Structs - Structs are called value types. - That means when a struct is assigned to a variable or constant or passed to a function its value is copied instead of increasing its reference count.
What fast enumeration?
Fast enumerationis a language feature that allows you toenumerate over the contents of a collection.
What is Struct and enum?
struct & enumvalue types. By default, the properties of a value typecannot be modifiedfrom within its instance methods. However, if you need to modify the properties of your struct or enum within a particular method, you can opt in tomutatingbehavior for that method.Mutatingis a keyword which enables a function parameter to modify their parameters. But in function it is not required.
Static function?
Staticfunctions are invoked by theclass itself, not by an instance.Staticfunctions can not beoverridden.
Class Functions?
Class functions(not instance methods) are alsostaticfunctions but they aredynamic dispatchedand can beoverriddenby subclasses unlikestaticfunctions.
Global Functions?
in
Swiftwhich isnot within a class and accessit anywhere in the project. ExampleMyAppName.appUtility()
Classes have additional capabilities that structures don’t have?
Inheritanceenables one class to inherit the characteristics of another.Structorenumcannot doinheritance. But they can confirm protocols.- Type casting enables you to check and interpret the type of a class instance at runtime.
Deinitializersenable an instance of aclassto free up any resources it has assigned.Referencecounting allows more than one reference to a class instance.- Unlike
structures,classinstances don’t receive a default memberwise initializer.
Note: If a
struct variable is private,memberwise initializers willbecomeprivate. we need to provide a public memberwise initializer in that case.Structsare much safer and bug-free, especially in a multithreaded environment.
Swiftvalue types are kept in the stack.
Even thoughstructandenumdon’t support inheritance, they are great forprotocol-orientedprogramming.
Classis a reference type and is stored in theheappart of memory which makes a class comparatively slower than a struct in terms of performance.
Astructis created on the stack. So, it is faster to instantiate (and destroy) a struct than a class.
What is the difference between struct and Enum?
- Struct cannot have a parameterless constructor
- Struct do not support inheritance.
- Struct can contain enum
- Struct can contain stored property
- struct alwase use computer and store property. stored property must be initialized in struct.
- Enums are a set of integer values.
- Enums define constants.
- Enum cannot contain Struct.
Enums in Swift have a few more features like you can add an initializer method or custom methods to extend the functionality. when creating an instance then you can provide an init method which defaults to one of the member values.
enum Type {
case Friend
case Family
case Coworker
case Other init() {
self = .Friend
}
}
Note
- We can also define functions , properties , extensions and protocols in Enumeration.
- Swift enumeration cases don’t have an integer value set by default, unlike languages like C and Objective-C.
- Enum can hold computerd property but not stored property"
What is the difference between static and singleton?
Singleton classcan have value when class objects are instantiated between server and client, such a way if three clients want to have a shared data between them singleton can be used. Singleton is not thread safe.
Static are always just shared and have no instance but multiple references.
# You introduce enumerations with the <enum> keyword and place their entire definition within a pair of braces.
enum APIErrorMessage {
case movieGenerEM
case searchMovieEM
case MovieDetailsEM
var test: String {
return "Enum computed propery"
}
init() {
self = .searchMovieEM
}
func getErrorMessage() -> String {
switch self {
case .MovieDetailsEM :return "Unable to fetch generes"
case .searchMovieEM:return "No result found for searched movie"
case .movieGenerEM:return "Unable to fetch movie detail"
default: return "We are facing some technical issue. Be right back"
}
}
}
## print(APIErrorMessage.MovieDetailsEM.getErrorMessage())
enum APIErrorMessageTwo {
case movieGenerEM, searchMovieEM, MovieDetailsEM
}
## When it isn’t appropriate to provide a case for every enumeration case, you can provide a default case to cover any cases that aren’t addressed explicitly
# Iterating over Enumeration Cases
enum MovieSections : CaseIterable {
case nowPlaying
case upcoming
case popular
case topRated
}
## Swift exposes a collection of all the cases as an allCases property of the enumeration type.
let numberOfSection = MovieSections.allCases.count
print("\(numberOfSection) movie section available")
// prints: 4 movie section available
for section in MovieSections.allCases {
print(section)
}
# Associated Values
## It’s sometimes useful to be able to store values of other types alongside these case values. This additional information is called an associated value.
enum URLEndpoints{
case fetchMovieGenere(String)
case searchMovie([String])
case fetchMovieDetail(Int)
// Computed variable
var urlEndpoint : String{
get{
switch self {
case .fetchMovieGenere(let genere):
return "https://www.URL.com/api/movieGenere/genere/" + genere
case .searchMovie(let queryArray):
return "https://www.URL.com/api/searchMovie/search/" + queryArray[0] + "/genere/" + queryArray[1]
case .fetchMovieDetail(let movieID):
return "https://www.URL.com/api/fetchMovie/movieId/" + String(describing: movieID)
}
}
}
}
print(URLEndpoints.fetchMovieGenere("Action").urlEndpoint)
// print: https://www.URL.com/api/movieGenere/genere/Action
print(URLEndpoints.searchMovie(["Fight", "Action"]).urlEndpoint)
// print: https://www.URL.com/api/searchMovie/search/Fight/genere/Action
print(URLEndpoints.fetchMovieDetail(9).urlEndpoint)
// print: https://www.URL.com/api/fetchMovie/movieId/9
## In the above example genre, queryArray and movieID are the associated value of the URLEndpoints enum
# Raw Values
enum APIErrorCodes : Int {
//Where EC means Error Code
case movieGenereEC = 400
case searchMovieEC = 401
case movieDetailEC = 402
}
## Here, the raw values for an enumeration called APIErrorCodes are defined to be of a type Int, and are set to some of the more common API error codes.
enum StaticEnum {
static let name = "Imtiaz"
static let name1 = "Imtiaz 1"
static let name2 = "Imtiaz 2"
}