Swift interview questions, Swift Interview Prep, iOS INTERVIEW QUESTIONS

अब Quizwiz के साथ अपने होमवर्क और परीक्षाओं को एस करें!

What is Singleton?

"A singleton class is a design pattern that only allows a single instantiated instance of a class. You do this by making the constructor private and having a static method that "getInstance" that will be a pointer to a local copy. NOTE, in general, it's NOT thread safe" From Apple: "Several Cocoa framework classes are singletons. They include NSFileManager, NSWorkspace, and, in UIKit, UIApplication and UIAccelerometer. The name of the factory method returning the singleton instance has, by convention, the form sharedClassType. Examples from the Cocoa frameworks are sharedFileManager, sharedColorPanel, and sharedWorkspace."

What is a call back?

"go off and do this operation, and when you're done, call this other function".

How many bytes can we send to apple push notification server?

256bytes

Escaping vs Non-Escaping?

@nonescaping closures: When passing a closure as the function argument, the closure gets execute with the function's body and returns the compiler back. As the execution ends, the passed closure gets out of scope and have no more existence in memory. Lifecycle of the @nonescaping closure: - Pass the closure as function argument, during the function call. - Do some additional work with the flow. - Function runs the closure. - Function returns the compiler back. @escaping closures: When passing a closure as the function argument, the closure is being preserved to be executed later and functions' body gets executed, returns the compiler back. As the execution ends, the scope of the passed closure exist and have existed in memory, till the closure gets executed.

What is Bundle Identifiers?

A bundle ID precisely identifies a single app. A bundle IS is used during the development process to provision devices and by the operating system when the app is distributed to customers. For example, Game Center and In-App Purchase use a bundle ID to identify your app when using these services. The preferences system using this string to identify the app for which a five preference applies. Similarly, Launch Services uses the bundle ID to locate an app capable of opening a particular file, using the first app it finds with the given identifier. The bundle ID is also used to validate an app's signature.

What is a completion handler

A completion handler is a closure ("a self-contained block of functionality that can be passed around and used in your code"). It gets passed to a function as an argument and then called when that function is done.

What does the defer keyword do?

A defer statement is used for executing code just before transferring program control outside of the scope that the statement appears in. func updateImage() { defer { print("Did update image") } print("Will update image") imageView.image = updatedImage } // Will update Image // Did update image If multiple statements appear in the same scope, the order they appear is the reverse of the order they are executed. The last defined statement is the first to be executed which is demonstrated by the following example by printing numbers in logical order. func printStringNumbers() { defer { print("1") } defer { print("2") } defer { print("3") } print("4") } /// Prints 4, 3, 2, 1

What is the use of guard?

A guard statement is used to transfer program control out of scope if one or more conditions aren't met. The value of any condition in a guard statement must be of type Bool or a type bridged to Bool. The condition can also be an optional binding declaration.

What's a memory leak?

A memory leak is a portion of memory that is occupied forever and never used again. It is garbage that takes space and causes problems. For Apple: "Memory that was allocated at some point, but was never released and is no longer referenced by your app. Since there are no references to it, there's now no way to release it and the memory can't be used again"

What is swift module?

A module is a single unit of code distribution. A framework or application that is built and shipped as a single unit and that can be imported by another module with Swift's import keyword. Each build target (such as an app bundle or framework) in Xcode is treated as a separate module in Swift.

What is a Swift Protocol?

A protocol is a set of methods, properties, etc. that are closely related in order to perform related functionality. Protocols can then be adopted by something (class, struct, enum) which then must provide their own implementation of the requirements. If a type fulfills all the requirements of a protocol, it conforms to the protocol. From Apple: "A protocol defines a blueprint of methods, properties, and other requirements that suit a particular task or piece of functionality. The protocol can then be adopted by a class, structure, or enumeration to provide an actual implementation of those requirements. Any type that satisfies the requirements of a protocol is said to conform to that protocol."

What are the differences between Library and Frameworks?

A static library is actually compiled as part of your app, whereas a framework is distributed with your app. Basically, frameworks ARE libraries and provide a handy mechanism for working with them. If you look "inside" a framework, it's just a directory containing a static library and header files (in some folder structure with metadata). If you want to create your own framework, you have to create a "static library" and pack it in a safe way.

Reuse identifier.

A string used to identify a cell that is reusable. The reuse identifier is associated with a UITableViewCell object that the table-view's delegate creates with the intent to reuse it as the basis (for performance reasons) for multiple rows of a table view. It is assigned to the cell object in initWithFrame:reuseIdentifier: and cannot be changed thereafter. A UITableView object maintains a queue (or list) of the currently reusable cells, each with its own reuse identifier, and makes them available to the delegate in the dequeueReusableCell(withIdentifier:) method.

What's a struct?

A struct is similar in capability to a Class, however Struct's are value types whereas Class'es are reference types

What is tuple?

A tuple is a group of different values represented as one. According to Apple, tuple type is a comma-separated list of zero or more types, enclosed in parentheses.

What is a tuple? How to create one?

A tuple is used to arrange multiple values in a single compound Value. In tuple, it is not compulsory for value to be of the same type. It can be of any type. For an instance, ("interview", 123) is a tuple having two values: one is string Type, and another one is an integer type. A tuple is a group of zero or more values represented as one value. They are commonly used to return multiple values from a function call. Tuple = Dictionary(can be created on the fly) + Struct (hold very specific types of data) There are two types of Tuple in swift 1.Named Tuple let nameAndAge = (name:"Midhun", age:7) Access the values like: nameAndAge.name //Output: Midhun nameAndAge.age //Output: 7 2. Unnamed Tuple In unnamed tuple we don't specify the name for it's elements. let nameAndAge = ("Midhun", 7) Access the values like: nameAndAge.0 //Output: Midhun nameAndAge.1 //Output: 7

What is a dynamic library

A unit of code and/or assets linked at runtime that may change. ** only apple is allowed to create dynamic libraries for iOS, for OS X you can create your own. **

What is a static library?

A unit of code linked at compile time, which does not change.

Wildcard Pattern

A wildcard pattern matches and ignores any value and consists of an underscore (_). for _ in 1...3 {}

What do we call dependencies of an object?

All the properties an object needs to function

Enumerations

An enumeration defines a common type for a group of related values and enables you to work with those values in a type-safe way within your code. Enums in Swift have a few more features like you can add an initializer method or custom methods to extend the functionality. If you didn't want to select a specific member value 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 } } /////////// A construct in Swift that allows us to model a finite grouping of data or a group of related types. Basically, it is a type that contains a group of various related values under the same umbrella.

Expression Pattern

An expression pattern represents the value of an expression. Expression patterns appear only in switch statement case labels. The expression represented by the expression pattern is compared with the value of an input expression using the Swift standard library ~= operator. The matches succeeds if the ~= operator returns true. By default, the ~= operator compares two values of the same type using the == operator. It can also match a value with a range of values, by checking whether the value is contained within the range, as the following example shows. let point = (1, 2) switch point { case (0, 0): print("(0, 0) is at the origin.") case (-2...2, -2...2): print("(\(point.0), \(point.1)) is near the origin.") default: print("The point is at (\(point.0), \(point.1)).") } // Prints "(1, 2) is near the origin."

What are extensions?

An extension allows you to add functionality to a class, struct, enum, protocol, etc. It's highly useful when you don't have access to the class (Such as the classes that are part of apple's iOS SDK/Framework) Can be used to conform to protocols. Can be used to organize code (conforming to protocols in extensions, keeps all the functionality of that protocol in the same place)

Identifier pattern

An identifier pattern matches any value and binds the matched value to a variable or constant name. For example, in the following constant declaration, someValue is an identifier pattern that matches the value 42 of type Int: let someValue = 42

What is an urlSession?

An object that coordinates a group of related network data transfer tasks. The URLSession class and related classes provide an API for downloading data from and uploading data to endpoints indicated by URLs. The API also enables your app to perform background downloads when your app isn't running or, in iOS, while your app is suspended. A rich set of delegate methods support authentication and allow your app to be notified of events like redirection.

What is a nil?

An optional that is not set.

Any and AnyObject

Any can represent an instance of any type at all, including function types. AnyObject can represent an instance of any class type.

Any vs Any Object.

AnyObject refers to any instance of a class and is equivalent to id in Objective-C. It's useful when you specifically want to work with a reference type because it won't allow any of Swift's structs or enums to be used. AnyObject is also used when you want to restrict a protocol so that it can be used only with classes. Any refers to any instance of a class, struct, or enum - literally anything at all. You'll see this in Swift wherever types are unknown or are mixed in ways that can be meaningfully categorized

Rules of the responder chain

Apps receive and handle events using responder objects. A responder object is any instance of the UIResponder class, and common subclasses include UIView, UIViewController, and UIApplication. Responders receive the raw event data and must either handle the event or forward it to another responder object. When your app receives an event, UIKit automatically directs that event to the most appropriate responder object, known as the first responder. Unhandled events are passed from responder to responder in the active responder chain, which is the dynamic configuration of your app's responder objects. generally how UIview -> UIwindow -> UIapplication -> applicationdelegate

Experience with different size classes and auto layout:

AutoLayout Defines relationships between objects, using constraints instead of defining what position an object should be in based on pixels. Allows the view to adapt to different screen sizes, since its relationship based The UI equivalent of SVG Size Classes Groups of screen sizes based on height and width 2 options for each, compact, and regular wC (compact width) hC (compact height) wR (regular width) hR (regular height) wCxhR, wCxhC, wRxhR, wRxhC Can set different constraints for different size classes using InterfaceBuilder and AutoLayout

Grand Central Dispatch (GCD) / NSOperation

Both technologies are designed to encapsulate units of work and dispatch them for execution. GCD is a low-level C API that interacts directly with Unix level of the system. NSOperation is an Objective-C API and that brings some overhead with it. Instances of NSOperation need to be allocated before they can be used and deallocated when they are no longer needed. Even though this is a highly optimized process, it is slower than GCD, which operates at a lower level. The NSOperation API is great for encapsulating well-defined blocks of functionality. GCD is ideal if you just need to dispatch a block of code to a serial or concurrent queue.

Classes vs Structures

Classes have additional capabilities that structures do not: Inheritance enables one class to inherit the characteristics of another. Type casting enables you to check and interpret the type of a class instance at runtime. Deinitializers enable an instance of a class to free up any resources it has assigned. Reference counting allows more than one reference to a class instance. Consider creating a structure when one or more of these conditions apply: The structure's primary purpose is to encapsulate a few relatively simple data values. It is reasonable to expect that the encapsulated values will be copied rather than referenced when you assign or pass around an instance of that structure. Any properties stored by the structure are themselves value types, which would also be expected to be copied rather than referenced. The structure does not need to inherit properties or behavior from another existing type.

What is a closure in Swift?

Closure: A block of code. Closures: Can be passed around and used in your code Can be parameters/arguments to functions Very useful if you want to wait for something to be done, and then run some code, like with a network call, you can wait for the data to get back, and then run the block of code that is the closure, or parameter, to your method.

Map vs Compact Map

Compact Map. Returns an array containing the non-nil results of calling the given transformation with each element of this sequence. Use this method to receive an array of non-optional values when your transformation produces an optional value. Map or flatMap returns an array containing the concatenated results of calling the given transformation with each element of this sequence. You would use this method to receive a single-level collection when your transformation produces a sequence or collection for each element.

Delegate vs notification.

Delegation allows an object to send a message to another object( the delegate), so that it can customize the handling of an event. The important point about delegation is the way it is implemented allows for minimal dependency between the delegating object and its delegate. The delegating object needs to have a reference to its delegate so that it can call methods in the delegate. Notification differs from the delegation in that it allows a message to be sent to more than one object. It is more like a broadcast rather than a straight communication between two objects. It removes dependencies between the sending and receiving objects by using a notification center to manage the sending and receiving notifications. The sender does not need to know if there are any receivers registered with the notification center. There can be one, many or even no receivers of the notification registers with the notification center. The other difference between notifications and delegates is that there is no possibility for the receiver of a notification to return a value to the sender.

What is dependency injection

Dependency Injection is an approach to organizing code so that its dependencies are provided by a different object, instead of by itself. Arranging code like this leads to a codebase of loosely-coupled components that can be tested and refactored.

Tell me about Swift Generics

Generics are a way of making one data type act in a variety of ways depending on how it is created.

How many types of variable scopes are there?

Global, Instance and Local

What is an optional

In Swift, nil means the absence of a value. Sending a message to nil results in a fatal error. An optional encapsulates this concept. An optional either has a value or it doesn't. Optionals add safety to the language. it's an enum under the hood with a .some and .none case. We can even work with these cases and also bind them to local constants. we call this pattern matching

Talk to me about downloads on the main thread.

In iOS the main thread executes synchronously. Synchronous queue means that operations run one after the other in order. For development purposes what that means is that if something is running synchronously, it waits for each operation to finish before moving on to the next one. UIApplication runs on the applications main thread. So, if there is an operation blocking your main thread takes a long time to complete, it could wreak serious havoc with your application.

What is the difference between windows and views?

In iOS, you use windows and views to present your application's content on the screen. Windows do not have any visible content themselves but provide a basic container for your application's views.

What is an in-out parameter

In-out parameter lets you change the value of a function parameter from within the body of that function. All parameters passed into a Swift function are constants, so you can't change them. If you want, you can pass in one or more parameters as inout, which means they can be changed inside your function, and those changes reflect in the original value outside the function. For example, if you want to double a number in place - i.e., change the value directly rather than returning a new one - you might write a function like this: func doubleInPlace(number: inout Int) { number *= 2 } To use that, you first need to make a variable integer - you can't use constant integers with inout, because they might be changed. You also need to pass the parameter to doubleInPlace using an ampersand, &, before its name, which is an explicit recognition that you're aware it is being used as inout. In code, you'd write this: var myNum = 10 doubleInPlace(number: &myNum) //returns 20

What are the main Integer types?

Int (signed) and Uint (unsigned) are the two main Integer types in Swift Programming.

Basic Data Types

Int, Float, Double, String, Character, Bool, Array, Dictionary

What is CoreData?

Is a framework that is used to manage the model layer objects in your application. It provides generalized and automated solutions to common tasks associated with object life cycle and object graph management, including persistence. Advantages Decreases by 50 to 70 percent the amount of code you write to support the model layer. This primarily due to the following built-in features that developer do not have to implement, test, or optimize: Change tracking and built-in management of undo and redo beyond basic text editing. Maintenance of change propagation, including maintaining the consistency of relationships among objects. Lazy loading of objects. Automatic validation of property values. Schema migration tools that simply schema changes and allow developers to perform efficient in-place schema migration. Optional integration with the application's controller layer to support user interface synchronization. Grouping, filtering, and organizing data in memory and in the user interface. Automatic support for storing objects in external data repositories. Effective integration with the macOS and iOS tool chains.

Identity Operators

It can sometimes be useful to find out if two constants or variables refer to exactly the same instance of a class. To enable this, Swift provides two identity operators: Identical to (===) Not identical to (!==)

Responder Chain

It is a hierarchy of objects that obtain the opportunity to respond to the events.

Explain what is half-open range operator

It is an operator (a<b) that is used to defines a range that runs from a to b but it doesn't contain b. The reason for its name that is half-open is that it does not contains its last value, just have its first value. The value of 'a' compulsory is not greater than b in the closed ranged operator. The resulting range will be empty in the case of a is equal to b. It is useful when you are working with zero-based lists like arrays where it is useful to calculate the length of the list. For example: let names = ["Alley", "Anna", "Jack", "Brian"] let count = names.count for i in 0..<count print("Person \(i + 1) is called \(names[i])") } // Person 1 is called Alley, Person 2 is called Anna, Person 3 is called Jack, Person 4 is called Brian

What is the difference between JSON and XML

JSON is so much more lightweight and less verbose

What is the security you have implemented in your apps?

Keychain service is the best place to store small secrets, like passwords and cryptographic keys. You use the functions of the keychain services API to add, retrieve, delete, or modify keychain items. Secure Transport using standardized transport layer security mechanisms. CryptoSwift is a growing collection of standard and secure cryptographic algorithms implemented in Swift. This method takes an account and password and saves a hashed string on Keychain instead of a direct string.

Explain lazy in Swift ?

Lazy initialization — technique for delaying the creation of an object or some other expensive process until it's needed. These properties can only use with class and struct member.Lazy properties are not thread safe because of not initialized automatically . You must always declare a lazy property as a variable (with the var keyword). Constant properties must always have a value before initialization completes, and therefore cannot be declared as lazy.

Give some examples for UInt usage

Math functions work the same as Int, with one exception: you have boundaries to watch for. All of these will work with no problems:

Differences between MVVM vs MVC?

Model-View-Controler (MVC) Is a software architectural pattern for implementing user interfaces on computers. Model: Your data model (the class or struct that is the model or models for your app) View: The UI component. The user can interact with the app via the View Controller: Responsible CRUD operations go here. The go-between for the Model and View. Would handle fetching the data, controlling the data and model, and providing the tools and functions so the View can configure and operate correctly Model-View-View-Model (MVVM) Adds a layer of abstraction Takes the business logic out of the View or View-Controller Provides access to the data model to the view in such a way that the objects are easily presented Model: Your data model View: The UI component of the app View-Model: the part of the app that provides access to the data in an easy to handle format, so the view is not responsible for any business logic.

Readers-Writers problem

Multiple threads reading at the same time while there should be only one thread writing.

Does Objective-C contain private methods?

NO. There is nothing called a private method in Obj-C. If a method is defined in .m only then it becomes protected. If in .h it is public.

Whats the difference between NSArray and NSMutableArray?

NSArray's contents can not be modified once it's been created whereas a NSMutalbeArray can be modified as needed. (Essentially items can be added and removed from it)

how many threading options are there?

NSThread GCD Operation Queue

In class inheritance, can you override a computed property with a stored one?

No, you can override a stored property as a computed one.

Do you know how to call an API/additional experience?

Once we have a valid URL where we are going to ask for data, best known as API, is the moment to make a request for this network. Most common way to do that is URLSessions class, which helps us to manage network requests. It can be created with our own settings, or just call share attribute which contain default setting for us. Then we are ready to create the request or task to the URL using dataTask function.

What kind of options does iOS provide for data persistence?

Persistance options: CoreData (Quick, SQLite database under the hod, can store custom objects, Apple provided API and framework, 1st party solution) KeyChain UserDefaults (It can only contains certain data types) SQLite Database Saving files directly to file system NSKeyedArchived (NSCoding) REALM (Third-Party Framework to help manage objects and a SQLite database) Property List (p-List Something every app has can store very little data, A solution)

raw vs associated values

Raw values are compile time-set values directly assigned to every case within an enumeration, as in the example detailed below: enum Alphabet: Int { case A = 1 case B case C } In the above example code, case "A" was explicitly assigned a raw value integer of 1, while cases "B" and "C" were implicitly assigned raw value integers of 2 and 3, respectively. Associated values allow you to store values of other types alongside case values, as demonstrated below: enum Alphabet { case A(Int) case B case C(String) }

what is a regular expression?

Regular expressions allow us to run complex search and replace operations across thousands of text files These are the special string patterns that describe how a search is performed through a string.

How many are there APIs for battery-efficient location tracking ?

Significant location changes — the location is delivered approximately every 500 metres (usually up to 1 km) Region monitoring — track enter/exit events from circular regions with a radius equal to 100m or more. Region monitoring is the most precise API after GPS. Visit events — monitor place Visit events which are enters/exits from a place (home/office).

What is the Xcode Target

Simple put its the instructions on building the app. A target specifies a product to build and contains the instructions for building the product from a set of files in a project or workspace. A target defines a single product; it organizes the inputs into the build system—the source files and instructions for processing those source files—required to build that product. Projects can contain one or more targets, each of which produces one product.

What differences are between Strong, Weak and Unowned references?

Strong: * Can be constant (let) * variable (var) * optional * or non-optional * increases retain count by 1 * default in Swift Weak: * variable only (var) * optional only (can not be non-optional) * does not increase retain count * typical use case is for delegates. You don't want to create a retain cycle between a delegator and a delegate. Unowned: * can be constant (let), * variable (var), * non-optional only (cannot be optional), * does not increase retain count * typical use case: capture list for a closure in order to avoid retain cycles From Apple: "Use a weak reference whenever it is valid for that reference to become nil at some point during its lifetime. Conversely, use an unowned reference when you know that the reference will never be nil once it has been set during initialization."

value types in Swift

Structures and Enumerations Are Value Types In fact, all of the basic types in Swift — integers, floating-point numbers, Booleans, strings, arrays and dictionaries — are value types, and are implemented as structures behind the scenes.

What Separates Structures and Classes?

Structures don't support inheritance. Part of the power of classes is that classes can inherit state and behavior from other classes. Even though structures don't support inheritance, structures can extend their functionality by conforming to protocols. Every instance of a structure keeps a copy of its data. Instances of a class share a copy of the data. Instances of classes are passed by reference. Type casting enables you to check and interpret the type of a class instance at runtime. Reference counting allows more than one reference to a class instance. Deinitializers enable an instance of a class to free up any resources it has assigned.

What are the different Access Levels in swift?

Swift provides five different access levels for entities within your code. Open access: Classes with open access can be subclassed or overridden by subclasses within the module where they're defined and within any module that imports the module where they're defined. Public access: Classes with public access can be subclassed or overridden by subclasses only within the module where they're defined. Internal access: enables entities to be used within any source file from their defining module, but not in any source file outside of that module. File-private access: restricts the use of an entity to its own defining source file. Private access: restricts the use of an entity to the enclosing declaration, and to extensions of that declaration that are in the same file. Open access is the highest (least restrictive) access level and private access is the lowest (most restrictive) access level. All entities in your code (with a few specific exceptions) have a default access level of internal.

What is the Decorator Design Pattern?

The Decorator pattern dynamically adds behaviors and responsibilities to an object without modifying its code. It's an alternative to subclassing where you modify a class's behavior by wrapping it with another object. In Objective-C there are two very common implementations of this pattern: Category and Delegation. In Swift there are also two very common implementations of this pattern: Extensions and Delegation.

when to use structs

The conclusion here is that anything that wraps (read: calls) the kernel really shouldn't be a struct. The implication being that you should not write structs that do: File I/O Networking Message passing Heap memory allocation etc. But if you consider what we're really saying, we're really saying you shouldn't wrap not just the kernel, but any singleton. Any singleton that you try and mess with from a struct will have this issue, becuase the references to those singletons don't get copied. So we can add to the list of things you shouldn't do with structs: Location stuff (you have 1 GPS) Screen-drawing stuff (you have 1 display) Stuff that talks to UIApplication.sharedApplication() etc. As a general guideline, consider creating a structure when one or more of these conditions apply: The structure's primary purpose is to encapsulate a few relatively simple data values.

What Is the Meaning of ! In Swift?

The exclamation mark is commonly used to explicitly force an operation. For example, to force unwrap (as opposed to safely unwrap) an optional, you'd use the exclamation mark.

Whats the difference between frame and bounds?

The frame of a view is the rectangle, expressed as a location (x,a) and size (width, height) relative to the superview it is contained within. The bounds of a view is the rectangle, expressed as location (x, y) and size (width, height) relative to its own coordinate system (0,0).

Explain some common execution states in iOS

The states of the common execution can be as follows: Not running - This state means that there is no code that is being executed and the application is completely switched off. Inactive - This state means that the application is running in the background and is not receiving any events. Active - This state means that the applications are running in the background and is receiving the events. Background - This state means that the application is executing the code in the background. Suspended - This state means that the application is in the background and is not executing.

Difference between stored and computed properties

The stored properties of the Car class store a value. The computed property, however, doesn't store a value. It calculates or computes a value based on the state (the values stored in sizeFuelTank and fuelEfficiency) of the Car instance.

types of error handling

There are four ways to handle errors in Swift. You can propagate the error from a function to the code that calls that function, handle the error using a do-catch statement, handle the error as an optional value, or assert that the error will not occur.

Type-Casting Patterns

There are two type-casting patterns, the is pattern and the as pattern. The is pattern appears only in switch statement case labels. The is and as patterns have the following form: is type pattern as type

Structure Initialization

They have an automatically-generated memberwise initializers, which you can use to initialize the member properties of new instances.

What is type casting?

Type casting is a way to check the type of an instance, or to treat that instance as a different superclass or subclass from somewhere else in its own class hierarchy. Casting does not actually modify the instance or change its values. The underlying instance remains the same; it is simply treated and accessed as an instance of the type to which it has been cast.

Initialize a UIAlertView

UIAlertView *alert = [UIAlertView alloc] init]; var alert = UIAlertView()

Outline the class hierarchy for a UIButton until NSObject.

UIButton inherits from UIControl -> UIControl inherits from UIView -> UIView inherits from UIResponder -> UIResponder inherits from the root class NSObject.

What are your options for saving things to the device?

UserDefaults Data Archiving and Unarchiving Property lists Keychain Saving Files Core Data

Var and let

Very simple: let is constant. var is dynamic. Bit of description: let creates a constant. (sort of like an NSString). You can't change its value once you have set it. You can still add it to other things and create new variables though. var creates a variable. (sort of like NSMutableString) so you can change the value of it.

View Controller Life Cycle:

ViewController lifecycle functions viewDidLoad() * called only once during the entire life of the VC * generally, this is a place where you can do an initial network call to begin to load data for the VC viewWillAppear() * called right before the view appears. Good place to refresh the data set you have from the network * good place to make some adjustments to the view, if needed * gets called every time the view is about to appear viewDidAppear() * called right after the view appears * gets called every time after the view appears viewWillDisappear() * called just before the view disappears * good place to cancel network calls for data/assets that are no longer needed viewDidDisappear() * also a good place to cancel network calls/loading of resources, etc. * called every time the view did disappear.

How to pass a variable as a reference?

We can pass variable as a reference using inout parameter. inout means that modifying the local variable will also modify the passed-in parameters. var value: String = "Apple" func changeString(newValue:inout String) { newValue = "Samsung" print(newValue) // Output:Samsung print(value) // Output:Samsung } changeString(newValue:&value)

mutating functions

What they really do logically is they generate a completely new version of the struct and assign the caller's reference to this new version. This means that var myInt = MyInt(2) myInt.mutatingIncrement() is really semantic sugar for var myInt = MyInt(2) myInt = MyInt(myInt.value + 1)

class vs protocol

When we need to define identity (what objects are) we should class and subclass. When we need to define what objects can do, we should do protocols and composition.

What is App Bundle?

When you build your iOS app, Xcode packages it as a bundle. A bundle is a directory in the file system that groups related resources together in one lace. An iOS app bundle contains the app executable file and supporting resource files such as app icons, image files and localized content.

In some cases, you can't avoid using implicitly unwrapped optionals. When? Why?

When you cannot initialize a property that is not nil by nature at instantiation time. A typical example is an Interface Builder outlet, which always initializes after its owner. In this specific case — assuming it's properly configured in Interface Builder — you've guaranteed that the outlet is non-nil before you use it. To solve the strong reference cycle problem, which is when two instances refer to each other and require a non-nil reference to the other instance. In such a case, you mark one side of the reference as unowned, while the other uses an implicitly unwrapped optional.

Is the delegate for CAAnimation retained?

Yes it is! The is one of the rare exceptions to memory management rules.

If I call performSelector:withObject:afterDelay: - Is the object retained?

Yes, the object is retained. It creates a timer that calls a selector on the current threads run loop. It may not be 100% precise time-wise as it attempts to dequeue the message from the run loop and perform the selector.

KVC

adds stands for Key-Value Coding. It's a mechanism by which an object's properties can be accessed using string's at runtime rather than having to statically know the property names at development time.

Readers-writer lock

allows concurrent read-only access to the shared resource while write operations require exclusive access.

Dispatch Barrier Block

create a serial-style bottleneck when working with concurrent queues.

what are labeled statement?

labeled statements allow us to name certain parts of our code, and it's most commonly used for breaking out of nested loops.

Race Condition

occurs when two or more threads can access shared data and they try to change it at the same time.

what is a Deadlock

occurs when two or sometimes more tasks wait for the other to finish, and neither ever does.

Difference between sort and sorted

sort mutates the array it is called on so its items are sorted. sorted returns a copy of the array it is called on with the values sorted. If the original order of your array is important, calling sort on it would cause serious problems. Also, if you have a giant array that contained value types and called sorted on it, it would duplicate each value and double the memory usage.

KVO

stands for Key-Value Observing and allows a controller or class to observe changes to a property value. In KVO, an object can ask to be notified of any changes to a specific property, whenever that property changes value, the observer is automatically notified.

When does layoutSubviews() get called?

whenever a view needs to recalculate the frames of its subviews

Control flow statements

while loops, repeat while loops, if, guard, switch, break, continue, for-in loop,


संबंधित स्टडी सेट्स

Pre-assesment - Introduction to Cryptography - C839 - WGU

View Set

Unit 29: Vehicle Owner Responsibilities

View Set

Managing Community Nutrition Programs Ch. 18

View Set

chapter 6 - marketing management

View Set

Power, Racism, and Privilege Midterm 1

View Set

Psych 311 - Exam #1 Multiple Choice

View Set