1) What is iOS Swift?
![Introducing Swift Programming Language](https://csharpcorner-mindcrackerinc.netdna-ssl.com/article/introducing-swift-programming-language/Images/image001.jpg)
Answer: Swift is a compiled and new programming language evolved by Apple Inc in June 2014 in order to develop apps for mobile and desktop. This language works for watchOS, macOS, iOS, and tvOS.
Apple created Swift language to work with both Cocoa Touch and Cocoa. Swift supports multiple operating systems such as Free BSD, Linux, Darwin, etc. This language was designed to work along with the Objective-C library and Cocoa framework in the Apple products.
2) What are the advantages of using Swift?
![](https://www.devopsschool.com/blog/wp-content/uploads/2022/02/advantages.png)
Answer: Swift programming language has speedily become one of the quick-growing languages in memoir. Swift makes us develop software that is incredibly fast, robust and secure.
This language is the most useful programming language that is used to develop an application for macOS and iOS(iPad and iPhone).
There are some important advantages offered by developing apps for macOS and iOS using swift.
Open-source language: The Swift programming language has been created as an open-source and is being open to everyone, this makes it simple for the program to upgrade all the source codes, email lists and bug tracker at regular intervals.
Easy to learn and maintain: Swift programing language is more simple and accurate when compared to C/C++. Apple evolved its programing language to be easy to use and syntaxes are taken from programming languages such as C#, Python, and Ruby. These simple syntax of this programing language make it more meaningful. In swift, all the content of the implementation (.m) and header (.h) files are combined in a single file that is (.swift).
Supported by multiple devices: Swift programming language is not just limited to support Apple devices, it will also support multiple devices of the technology world like Linux and Windows devices.
Supports dynamic libraries: Dynamic libraries are the executable chunks of the code that can be connected to an app. This feature allows the latest swift programing language. In swift, dynamic libraries are directly uploaded to the memory, thereby resulting in deduction down on the initial size of the app and finally increases app performance.
Optional types: An optional in swift is a type that can be held either as a value or not. To declare an optional, we can use a question “?” mark.
Closures: Closures are self-contained blocks of functionality that can be passed around and used in our code.
3) Explain Swift vs Objective-C?
Answer: Enlisted below are the various differences between Swift vs Objective-C.
Swift is an object-oriented and functional programing language, whereas Objective-C is a class-based object-oriented programing language.
Swift supports dynamic libraries, whereas Objective-C does not support dynamic libraries.
Swift supports Tuples, whereas Objective-C does not support Tuples.
Semicolons are not required in Swift, whereas semicolons are required in Objective-C.
Swift is an open-source programing language, whereas Objective-C is limited to Apple, and it’s not an open-source language.
We have to use the “let” keyword to declare for constant and “var” keyword to declare for a variable, whereas in objective C, we have to declare the variable as “NSString” and constant as “int”.
Swift enables us to define methods in structure, classes or enumeration, whereas Objective C does not allow this.
In swift, we can define classes in a single file (.swift), whereas in Objective C we create separate interface (.h) files for classes and implementation (.m) files for classes.
4) Where can we test the apple iPhone apps if we don’t have an iOS device?
Answer: If we don’t have an iOS device, we can test our application on simulators provided by Apple on the Mac system.
5) What are the tools that are required to develop iOS applications?
Answer: These are some of the essential tools that we should have:
Mac/MacMini: It is necessary for us to get a Mac with the Intel-based processor running on Mac OS. Not to worry, if we have our own PC, we can still develop iOS apps through Mac Mini.
Xcode: Xcode is the Apple IDE (Integrated Development Environment) that is used for both iOS apps and MAC OS. It provides us a visual layout editor and a code editor that can deal with the logic, user interface and response behind the scene.
Swift Programming Language: In the code editor, the logic will be written in a programming language that is invented by Apple, called Swift.
Apple Developer Program: This program allows the developer to push our app live on the App store so that the customers and downloaders all over the world can download our app and use it.
6) What are the most important features of swift?
![](https://www.devopsschool.com/blog/wp-content/uploads/2022/02/features-1024x648.png)
Answer: Some important features of swift are given below:
- More impressive structs and enums
- Protocol oriented
- Optional Types
- Type Safety and Type inference language
- Not required to use semicolons
- Enforced initializers
- Safe by default
- Less code, fewer files
- Forced Unwrapping
- Tuples
- Closures
- Much faster when compared to other languages.
7) Explain the common execution states for a swift iOS App (iOS Application Lifecycle)?
Answer: The 5 common execution states are as follows:
Not Running: This is a simple state in which our app is not launched or no code is being executed and terminated by the system and the application is completely switched off.
Inactive: This state is just a transitional state. Inactive state means our application is running in the background but is not able to receive events.
Active: Active state is the main execution state, where our app is running in the background and is able to receive events.
Background: This is the state where our App is running in the background and still is able to execute the code in the background.
Suspended: This state means that our app running is in the background state and the system suspends this app and the application cannot execute any code.
8) Is Swift an object-oriented programming language?
Answer: Yes, swift is an object-oriented programming language.
9) What type of objects are basic data types in swift?
Answer: Swift uses a standard set of basic data types for different purposes such as Boolean values, numbers, and strings.
Int: int is used to store the integer value.
Double and Float: Double and Float in swift are considered when while working with the decimal numbers.
Bool: The bool type is used to store the Boolean value. In swift, it uses true and false conditions.
String: In String literals, the user defines the text that is enclosed by double quotes in Swift.
Arrays: Arrays are the collection of list items.
Dictionaries: A dictionary is an unordered collection of items of a particular type that is connected with a unique key.
10) What is init() in Swift?
Answer: Initialization is a process of preparing an instance of an enumeration, structure or class for use.
Initializers are also called to create a new instance of a particular type. An initializer is an instance method with no parameters. Using the initializer, we can write the init keyword.
______________________________________________
init()
{
// perform some New Instance initialization here
}
_______________________________________________
11) What are the control transfer statements that are used in iOS swift?
Answer: The control transfer statements that are used in iOS swift include:
- Return
- Break
- Continue
- Fallthrough
12) What is the difference between Let and Var in swift?
Answer: In swift language, we can declare a constant and variable using Let and Var keyword.
(i) Let: Let keyword is immutable, it’s used to declare a constant variable, and the constant variable cannot be changed once they are initialized.
For Example: let myAge = 25
We cannot change the value of age, you can declare the constant value of it only once using the let keyword.
(ii) Var: Var keyword is mutable, and is used to declare a variant variable. These variant variables can change the run time.
For Example:
var myName = “Dell”
we can change the value of name = “Apple”.
13) How to add an element into an Array?
Answer: Arrays are one of the most used data types in an application (app). We use arrays to organize our application (app) data.
Swift makes it easy to create an array in our code using an array literal. Array elements are simply surrounded by a comma and the list of values is separated with square brackets.
For Example,
________________________________________________________________
// Add ‘Int’ elements in an Array
let natural number = [1, 2, 3, 4, 5, 6, 7]
// Add ‘String’ elements in an array
let countryName = [“India”, “Japan”, “Malaysia”, “Peru”, “Russia”]
__________________________________________________-
14) Which JSON framework is supported by iOS?
Answer: SBJson framework is supported by iOS. SBJson framework provides additional control and a flexible API which makes JSON handling easier. It is a well and highly flexible framework that supports the flexible functioning of APIs.
Q #15) What is PLIST in iOS?
Answer: PLIST stands for Property List. PLIST is basically a dictionary of value and keys that can be stored in our file system with a .plist file extension. The property list is used as a portable and lightweight means to store a lesser amount of data. They are normally written in XML.
Different types of property lists are mentioned below:
Binary Property List
XML Property List
ASCII Legacy Property List
16) What is a dictionary?
Answer: Dictionaries are an association of an unordered collection of key-value pairs. Each value is associated with a unique key, which is a hashable type such as a number or string. We can use the dictionary concept in swift programming language whenever we want to obtain the values based on a key value.
Syntax of Swift Dictionaries:
Following is the syntax of defining a dictionary in the Swift programming language.
________________________
Dictionary ()
_____________________
Or
_______________________________
[Key: Value] () Creating Dictionaries in Swift:
Following are the different ways of creating a dictionary with key-value pairs in the declaration.
_______________________________
// using Dictionary Var names = Dictonary () Names = [“Ajay”: 1, “Mohit”: 2] print(names) // it prints [Ajay: 1, Mohit: 2] _____________________________
17) What is a Protocol in swift?
Answer: The protocol is a very common feature of the Swift programming language and the protocol is a concept that is similar to an interface from java. A protocol defines a blueprint of properties, methods, and other requirements that are suitable for a particular task.
In its simplest form, the protocol is an interface that describes some methods and properties. The protocol is just described as the properties or methods skeleton instead of implementation. Properties and methods implementation can be done by defining enumerations, functions, and classes.
Protocols are declared after the structure, enumeration or class type names. A single and multiple protocol declaration can be possible. Multiple protocols are separated by commas.
We can define a protocol in a way that is very similar to structures, enumerations, and classes:
_______________________________________
Protocol Someprotocol { // protocol definition goes here } ___________________________________
We can define multiple protocols, which are separated by commas:
____________________________________________
Class SomeClass: SomeSuperclass, Firstprotocol, Secondprotocol { // Structure definition goes here } _____________________________________
18) What is a delegate in swift?
Answer: Delegate is a design pattern, which is used to pass the data or communication between structs or classes. Delegate allows sending a message from one object to another object when a specific event happens and is used for handling table view and collection view events.
Delegates have one to one relationship and one to one communication.
19) What is the use of double question mark “??” in swift?
Answer: The double question mark “??” is a nil-coalescing operator, it is mainly a shorthand for the ternary conditional operator where we used to test for nil. A double question mark is also used to provide a default value for a variable.
stringVar ?? “default string”
This exactly does the common thing, if stringVar is not nil then it is returned, otherwise the “default string” is returned.
20) What is a GUARD statement? What is the benefit of using the GUARD statement in swift?
Answer: A GUARD statement is used to transfer the program control out of the scope when one or more conditions are not met. Using this statement helps in avoiding the pyramid of doom.
A GUARD statement will be in the following form:
______________________________________________________________________________________________
guard condition else
{
Statements
}
__________________________________________________
21) What are the collection types that are available in swift?
Answer: There are three primary collection types that are available in swift for storing a collection of values. They are dictionaries, sets, and arrays
Arrays: Arrays is an ordered collection of values, which is stored in the same type of values in an ordered list.
Sets: Sets are an unordered collection of unique values, which are stored in a distinct value of the same type in a collection without any defined ordering.
Dictionaries: Dictionaries are an unordered collection of Key and value pair associations in an unordered manner.
22) What is the difference between Array and NSArray?
Answer: The difference between Array and NSArray are given below:
An array can hold only one type of data, whereas NSArray can hold different types of data.
An array is a value type, whereas NSArray is an immutable reference type.
23) What is “defer”?
Answer: The “defer” is a keyword that provides a block of code that can be executed while the execution is leaving the current scope.
24) What is the difference between class and structure?
Answer: The difference between class and structure are given below:
Classes are reference types, whereas structs are value types.
Classes can be built on other classes, whereas struct cannot inherit from another struct.
Classes have an inheritance, whereas structs cannot have an inheritance.
In class, we can create an instance with “let” keywords and attempt to mutate its property, whereas there is no Mutability in Structs.
Classes have Type Casting, whereas struct doesn’t have Type Casting.
27) How to create a constant in Swift programming?
Answer: We have to use the “let” keyword to declare a constant in the Swift Programming.
28) What Causes an Error in This Piece of Code? How Could You Fix It?
_____________________________
<!-- wp:paragraph -->
<p>let n1: Int = 1<br>let n2: Float = 2.0<br>let n3: Double = 3.34</p>
<!-- /wp:paragraph -->
<!-- wp:paragraph -->
<p>var result = n1 + n2 + n3</p>
<!-- /wp:paragraph -->
______________________________
Answer – In Swift, implicit type casting between two data types is not possible.
In the code above, you’re trying to add three elements together, each of which represents a different data type.
To fix this, you need to convert each value to the same data type. For example:
____________________________________________________________
var result = Double(n1) + Double(n2) + n3 _____________________________________
29) What Are Enumerations in Swift?
An enumeration is a group of related values.
Enumerations make it possible to write type-safe code.
______________________________________
enum Direction { case North case East case South case West } ________________________________
Now, in your code, you can call Direction.North, for example, instead of using a mystic string “North” (that could easily be misspelled and cause annoying bugs).
30) What is typealias in Swift? How Do You Create One?
Typealias, as the name suggests, is an alias for an existing data type.
You can create one like this:
______________________________
typealias Weight = Float _____________________________________
Now you can use Weight instead of Float:
________________________________________
let mass1: Weight = 150.0 let mass2: Weight = 220.0 ___________________________________________
let total: Weight = mass1 + mass2
31) How Can You Improve Code Readability?
In our company, we have 20 developers and 20 unique coding styles. How might we enforce some common coding styles/best practices?
Answer:
Start using a linter, such as Swiftlint. A linter is an easy-to-setup tool that checks and fixes your mistakes and enforces best practices and conventions on your behalf.
You can use the linter’s default guidelines, but you can also configure the linter to match your company’s preferences.
32) What Is a Completion Handler in Swift?
Completion handlers are closures in action.
Suppose you perform a time-consuming task, such as a network request, and you want to do something immediately after the request completes. But you definitely don’t want to waste resources by checking multiple times if the process is ongoing or not.
This is where completion handlers are used. A completion handler is a closure that “calls you back” as soon as the time-consuming process completes.
33) Let vs Var in Swift?
In Swift, you can use let to create a constant (a value that cannot be changed) and var to create a variable (a value that can be modified later).
34) What Is the Guard Statement?
A guard statement is used to transfer program control out of scope. Guard statement is similar to the if statement, but it runs only when some conditions are not met.
For example, a guard statement used to exit a function:
______________________________
func myFun() { guard false else { print("This block is run") return } print("This is never run") } _________________________________________
myFun()
Output:
_____________________________
This block is run __________________________
35) What Are the Three Primary Collection Types in Swift?
Arrays: An array is an ordered collection of values.
Sets: A set is an unordered collection of values.
Dictionaries: A Dictionary is an unordered collection of key-value pairs.
36) What is Optional Chaining?
![](https://www.devopsschool.com/blog/wp-content/uploads/2022/02/optional-123-1024x484.png)
Optional chaining means you can safely call a property of something that may be nil.
Optional chaining works, as the name suggests, by chaining one or more optional values with a question mark operator ?, like this:
____________________________________
something?.someValue?.someMethod() ___________________________________
If nil is encountered at any point in the above chain, the app won’t crash — instead, a nil is returned.
37) What Classes and Structs have in common in Swift and what are their differences?
The features classes and structs have in common:
- Both structs and classes can define properties to store values, and they can define functions
- They can define subscripts to provide access to values with subscript syntax
- They can define initializers to set up their initial state, with init()
- They can be extended with extension (this is important!)
- They can conform to protocols, for example to support Protocol Oriented Programming
- They can work with generics to provide flexible and reusable types
Classes support a few more capabilities that structs don’t have:
Classes can inherit from another class, like you inherit from UIViewController to create your own view controller subclass
Classes can be deinitialized, i.e. you can invoke a deinit() function before the class is destroyed
Classes are reference types and structs are value types
*Value Type: When you copy a value type (i.e., when it’s assigned, initialized or passed into a function), each instance keeps a unique copy of the data. If you change one instance, the other doesn’t change too.
*Reference Type: When you copy a reference type, each instance shares the data. The reference itself is copied, but not the data it references. When you change one, the other changes too.
38) What’s the difference between a protocol and a class in Swift?
Answer
In their basic form, a protocol describes what an unknown type of object can do. You might say it has two or three properties of various types, plus methods. But that protocol never includes anything inside the methods, or provides actual storage for the properties.
In a more advanced form, you can write extensions on your protocols that provide default implementations of the methods. You still can’t provide storage for properties, however.
In comparison, classes are concrete things. While they might adopt protocols – i.e., say they implement the required properties and methods – they aren’t required to do that. You can create objects from classes, whereas protocols are just type definitions. Try to think of protocols as being abstract definitions, whereas classes and structs are real things you can create.
39) When to use strong, weak and unowned references?
Answer
To determine if you even need to worry about strong, weak, or unowned, ask, “Am I dealing with reference types”. If you’re working with Structs or Enums, ARC isn’t managing the memory for those Types and you don’t even need to worry about specifying weak or unowned for those constants or variables.
Strong references are fine in hierarchical relationships where the parent references the child, but not vice-versa. In fact, strong references are the most appropraite kind of reference most of the time.
When two instances are optionally related to one another, make sure that one of those instances holds a weak reference to the other.
When two instances are related in such a way that one of the instances can’t exist without the other, the instance with the mandatory dependency needs to hold an unowned reference to the other instance.
40) When to use a set rather than an array in Swift?
Answer
You should use a set rather than an array if all the following criteria are true:
- You intend to add each item only once. Sets never allow duplicates.
- You don’t care about the order of the items in the set.
- You don’t need to use APIs that require arrays.
- You’re storing Hashable types, either your own or one of Swift’s built-in types likes strings and integers. Sets use hash values for fast look up of items.
41) When would you use self in a method?
Answer
By far the most common reason for using self is inside an initializer, where your likely to want parameter names that match the property names of your type, like this:
_________________________
<!-- wp:paragraph -->
<p>struct Student {<br>var name: String<br>var bestFriend: String</p>
<!-- /wp:paragraph -->
<!-- wp:code -->
<pre class="wp-block-code"><code>init(name: String, bestFriend: String) {
print("Enrolling \(name) in class…")
self.name = name
self.bestFriend = bestFriend
}</code></pre>
<!-- /wp:code -->}
__________________________________________
42) What Is Swift Messages?
Swift Messages is a library used to display messages as a status bar at the top or at the bottom of the iOS device’s screen.
43) What Are Generics? Give an Example of Using Generics?
Generics allows you to write flexible and reusable code that can work with any data type.
Imagine you’re writing a 3D vector structure, but you want to be able to create vectors using integers, floats, and doubles. You definitely don’t want to write the same code for each data type separately.
This is where you can use generics.
For example, you can create a generic type for parameters (to represent any type) using a letter e.g. T like this:
_______________________
struct Vec3D {
let x, y, z: T
init(x: T, y: T, z: T) {
self.x = x
self.y = y
self.z = z
}
}
let intVector = Vec3D(x: 1, y: 2, z: 5)
let floatVector = Vec3D(x: 1.0, y: 2.0, z: 5.0)
________________________________________
44) What Are Extensions?
In Swift, you can use extensions to add functionality to an existing type.
In Swift, you can create an extension by using the extension keyword:
_________________________________
extension SomeExistingType { // add new functionality here } ____________________________________
45) What Is a Nested Function?
A nested function is a combination of a function inside a function:
_________________________
func outer() { func inner() { // Do something here } } __________________________
46) What Functions Are in Swift?
![](https://www.devopsschool.com/blog/wp-content/uploads/2022/02/1234.png)
A function makes it possible to define reusable blocks of code. A function can perform a task that’s part of your program.
Usually, functions take some values that they can work with.
47) Nil vs None in Swift?
There is no difference between the two:
______________________________
nil == .none // returns true __________________________
The only “difference” is using nil is more common than using none.
48) What Is a Deinitializer? How to Create One?
A deinitializer is run before a class instance is deallocated.
You can create a deinitalizer by using the deinit keyword.
This method is useful only if you need to do some housekeeping before deallocating a class instance. Most of the time it’s enough to let Swift handle it automatically on your behalf.
Here is an example of a deinitializer that sets number back to 0 when an instance of Example is deallocated.
__________________________
<!-- wp:paragraph -->
<p>var number = 15</p>
<!-- /wp:paragraph -->
<!-- wp:paragraph -->
<p>class Example {<br>init() {<br>number *= 10<br>}</p>
<!-- /wp:paragraph -->
<!-- wp:code -->
<pre class="wp-block-code"><code>deinit {
number = 0
}</code></pre>
<!-- /wp:code -->
<!-- wp:paragraph -->
<p>}</p>
<!-- /wp:paragraph -->
_______________________
49) What are the different ways to pass data in swift?
Answer: There are several ways to pass data in swift such as KVO, Delegate, NSNotification & Callbacks, Target-Action, etc.
50) Explain how multiple line comment can be written in swift?
Multiple line comment can be written as forward-slash followed by an asterisk (/) and end with an asterisk followed by a forward slash (/).
- Implementing Managed IT Services: A Step-by-Step Guide - August 30, 2024
- DevOps Foundation Certification - August 29, 2024
- SRE Foundation Certification - August 29, 2024