What is swift programming?
Swift is a multi-paradigm new programming language developed by Apple Inc for OS X, iOS, tvOS and watchOS applications. It builds on the best parts of C and objective -C, without being constrained by its compatibility. It adopts safe patterns for programming and puts in more features in order to make the programming more flexible and easier. It is an innovative programming language for Cocoa and Cocoa Touch.
Why swift?
Swift is the most-advanced programming language used in future.
It is a safe by default
Swift is compatible with existing Objective-C libraries.
The improvements in app quality and stability over a huge developer community.
Swift includes things like more pervasive strong typing through generics and type inference.
There’s no problem with writing new modules in Swift that interoperate with existing Objective-C code bases.
What are the features of Swift Programming language?
- Safe and Fast
- It eliminates entire classes of unsafe code
- Arrays and integers are checked for overflow
- Variables are always initialized before use
- Memory is managed automatically
- Concise and fast iteration over a collection or range.
- Structs which support extensions, methods and protocols.
- Functional programming patterns.
- Advanced control flow
- Multiple return values and Tuples.
- Powerful error handling
What is the difference between Swift language and Objective-C language?
Swift Language:
- Swift is the programming language which was developed by Apple Inc for iOS.
- Swift brings type safety to iOS development and because of the static type can optimize call and directly call the methods or virtual table.
- Swift supports tuples, values which store groups of other values. Unlike arrays, the values in a tuple don’t have to all be the same type.
- Swift is best used in modern code syntax (like C#, Java, Go, Rust)
- Learning Swift is easier than Objective-C for C# / Java / Go developers
- Coding difference is Closure, generic, type interference, multiple return type, namespaces.
- Swift strings are improvement over Objective-C without worrying about using a mutable or immutable string type.
- Features: Design for safety, fast and powerful, interactive playgrounds, Objective-C interoperability, sytax improvement.
Objective –C Language:
- Objective-C is extension to C and purely Object-Oriented (oo) based programming language.
- Dynamic typing is support means type of the object it points is not checked at compile time. In addition, you can add methods to existing classes at run-time.
- No support for tuples in Objective-C. But in Objective-C, we can use blocks in similar fashion, but it’s not as straightforward or elegant.
- Objective-C is best used in much more 3rd-party libs and frameworks are available.
- Easy to learn after C / C++
- Coding difference is Semicolons required, type must be declared, header files, pointers, alloc and init.
- By using NSString objective-C string is represented and it’s a subclass of NSMutableString which provide many different ways to creating objects. The simplest way is by using @”..”.
- Features: Automatic Reference Counting (ARC), Dynamic run-time, NSNumbers, NSDictionary and NSArray literals, dynamic typing, Categories, Automatic garbage collection.
Write a basic program in Swift to print “My name is jack
import UIKit
var myString = “My name is jack”
println(myString)
Output: My name is jack
What is the difference between functions and methods in Swift?
In Swift,Both are functions in the same terms any programmer usually knows of it. That is, self-contained blocks of code ideally set to perform a specific task. Functions are globally scoped while methods belong to a certain type.
How to convert NSArray to NSMutableArray in swift programming?
We can convert the Swift Array to a MutableArray by using the following code.
let myArray: NSArray = [“iOS”,”Android”,”PHP”]
var myMutableArray = NSMutableArray(array:myArray)
print(myMutableArray)
What are the type of integers does Swift language have?
Swift provides unsigned and signed integers in 8, 16, 32 and 64-bit forms. Similar to C these integers follow a naming convention. For instance, unsigned integer is denoted by type UInt8 while 32-bit signed integer will be denoted by type Int32.
What is de-initializer and how it is written in Swift language?
A de-initializer is declared immediately before a class instance is de-allocated. You write de-initializer with the deinit keyword. De-initializer is written without any parenthesis, and it does not take any parameters. (Or) If you need to perform additional cleanup of your custom classes, it’s possible to define a block called deinit.
It is written as
deinit {
// perform the deinitialization
}
What is the question mark (? )in Swift language?
In Swift, the question mark (?) is used during the declaration of a property, as it tells the compiler that this property is optional. The property may hold a value or not, in the latter case it’s possible to avoid runtime errors when accessing that property by using ?. This is useful in optional chaining (see below) and a variant of this example is in conditional clauses.
var optionalName : String? = “sam”
if optionalName != nil {
print(“Your name is \(optionalName!)”)
}
What are optional binding and optional chaining in Swift?
Optional bindings or chaining come in handy with properties that have been declared as optional.
Optional chaining: Optional chaining is the way by which we try to retrieve a values from a chain of optional values. If you were to access the courses property through an exclamation mark (!) , you would end up with a runtime error because it has not been initialized yet. Optional chaining lets you safely unwrap this value by placing a question mark (?), instead, after the property, and is a way of querying properties and methods on an optional that might contain nil. This can be regarded as an alternative to forced unwrapping.
Optional binding: Optional binding is a term used when you assign temporary variables from optional in the first clause of an if or while block. Consider the code block below when the property courses have yet not been initialized. Instead of returning a runtime error, the block will gracefully continue execution.
What is the syntax for external parameters?
The external parameter precedes the local parameter name.
Func yourFunction (externalParameterName localParameterName: Type, ….) { …. }
A concrete example of this would be:
Func send Message (from name1: String, to name2: String) {print (“Sending message from \ (name1) to \ (name2)”)}
What are the Tokens in Swift programming?
A Swift program contains different tokens and a token may be a keyword, an identifier, a string literal, a constant, or a symbol. For instance, the below Swift statement contains three tokens:
Println (“Test!”)
The individual tokens are:
Println (
“Test!”
)
What is the different between let and var in swift?
Let: let keyword in swift is used to declare constant value and immutable can never be changed once defined.
let name =”jack”
After you can change name = “john” then you got compiler error. So, declare value of its only one time using let keyword.
Var: var keyword is mutable in swift is used to declare variant value that value can change at run time. It means can change it too many times.
var name = “jack”
You can change name = “john” then successfully updated value of variable.
What is Typecasting in swift?
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.Type casting in Swift is implemented with the is and as operators. These two operators provide a simple and expressive way to check the type of a value or cast a value to a different type.
What is error handling? How should one handle errors in Swift?
Error handling is the process of responding to and recovering from error conditions in your program. Swift provides first-class support for throwing, catching, propagating, and manipulating recoverable errors at runtime. The method for handling errors in Swift differ a bit from Objective-C. In Swift, it’s possible to declare that a function throws an error. It is, therefore, the caller’s responsibility to handle the error or propagate it. This is similar to how Java handles the situation.
You simply declare that a function can throw an error by appending the throws keyword to the function name. Any function that calls such a method must call it from a try block.
func canThrowErrors() throws -> String
//How to call a method that throws an error
try canThrowErrors()
//Or specify it as an optional
let maybe = try? canThrowErrors()</pre>
What are the collection types in Swift?
Collection Types: Swift has three primary collection types, they are arrays, sets, and dictionaries, for storing collections of values. Arrays are ordered collections of values and Sets are unordered collections of unique values. Dictionaries are unordered collections of key-value pair.
ARRAYS: An array stores values in an ordered list of the same type. The same value can appear in an array multiple times at different positions, So it can contain a duplicate value. Swift’s Array type is attached or can say bridged to Foundation’s NSArray class.
SETS: Set stores unique values of the same type in a collection with no defined ordering in it. We can use a set instead of an array when the order of items is not so important, or when you need to ensure that an item only appears once in the variable.
Dictionaries: A dictionary stores pair of value, which is between keys of the same type and values of the same type in a collection with no defined ordering. Every value is associated with a unique key, which acts as an identifier for that value within the dictionary. Items in an array have specified order but items in a dictionary do not have a specified order. Dictionary is used when you need to look up values based on their identifier, it’s similar to a real-world dictionary is used to see the definition for a particular word.
What is the use of exclamation mark ! in Swift?
Highly related to the previous keywords, the! is used to tell the compiler that I know definitely, this variable/constant contains a value and please use it (i.e. please unwrap the optional). From question 1, the block that executes the if condition is true and calls a forced unwrapping of the optional’s value.
What is type aliasing in Swift language?
This borrows very much from C/C++. It allows you to alias a type, which can be useful in many particular contexts.
typealias AudioSample = UInt16
What is a guard statement in Swift language?
Guard statements are a nice little control flow statement that can be seen as a great addition if you’re into a defensive programming style (which you should!). It basically evaluates a boolean condition and proceeds with program execution if the evaluation is true. A guard statement always has an else clause, and it must exit the code block if it reaches there.
guard let courses = student.courses! else {
return
}
What is the use of enumerate () function in Swift array?
This function is used to return the index of an item along with its value.
How to convert Swift String into an Array?
let Ustring : String = “My name is Jack”
let characters = Array(Ustring.characters)
print(characters)
What is ARC in Swift language?
ARC is stands for Automatic reference counting. Swift uses Automatic Reference Counting (ARC) to track and manage your app’s memory usage. It is used for Memory Management and provides information about the relationships between our code instances. It is also is used to initialize and deinitialize the system resources.
What is the Closures in Swift?
Closures are self-contained blocks of functionality that can be passed around and used in your code. Closures in Swift are similar to blocks in C and Objective-C and to lambdas in other programming languages.Closures can capture and store references to any constants and variables from the context in which they are defined. This is known as closing over those constants and variables. Swift handles all of the memory management of capturing for you.
What are control flow statements in swift?
Swift provides a variety of control flow statements. These include while loops to perform a task multiple times; if, guard, and switch statements to execute different branches of code based on certain conditions; and statements such as break and continue to transfer the flow of execution to another point in your code. Swift also provides a for-in loop that makes it easy to iterate over arrays, dictionaries, ranges, strings, and other sequences.
Why a compile time error occurs. How can you fix it?
Structures are value types. By default, the properties of a value type cannot be modified from within its instance methods.However, you can optionally allow such modification to occur by declaring the instance methods as ‘mutating’; e.g.:
struct IntStack {
var items = [Int]()
mutating func add(x: Int) {
items.append(x) // All good!
}
}
What is the use of hasPrefix(prefix: String) function in Swift?
hasPrefix(prefix: String) function: This String function is used to check whether a given parameter string exists as a prefix of the string or not.
What are the types of built-in data types available in Swift language?
The types of built-in data types available in Swift language are:
- Int or UInt
- Float
- Optional
- Double
- Bool
- String
- Character
What is the use of fallthrough statement in Swift language?
fallthrough statement: This statement is used to simulate the behavior of swift switch to C-style switch.
What is Lazy stored properties in swift? And when it is useful?
Lazy stored properties are used for a property whose initial values is not calculated until the first time it is used. You can declare a lazy stored property by writing the lazy modifier before its declaration. Lazy properties are useful when the initial value for a property is reliant on outside factors whose values are unknown.
What are the generics in swift?
Generic code enables you to write flexible, reusable functions and types that can work with any type, subject to requirements that you define. You can write code that avoids duplication and expresses its intent in a clear, abstracted manner. Generics are one of the most powerful features of Swift, and much of the Swift standard library is built with generic code. In fact, you’ve been using generics throughout the Language Guide, even if you didn’t realize it.
Explain inheritance in swift?
A class can inherit methods, properties, and other characteristics from another class.
When one class inherits from another, the inheriting class is known as a subclass, and the class it inherits from is known as its superclass. Inheritance is a fundamental behavior that differentiates classes from other types in Swift. Classes in Swift can call and access methods, properties, and subscripts belonging to their superclass and can provide their own overriding versions of those methods, properties, and subscripts to refine or modify their behavior. Swift helps to ensure your overrides are correct by checking that the override definition has a matching superclass definition.
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 (*/).
What are the collection types available in Swift with example?
In Swift, collection types come in three varieties Array and Dictionary and sets
Array: You can create an Array of a single type or an array with multiple types. Swift usually prefers the former one
Example for single type array is,
Var card Name: [String] = [“Jack”, “Leena”, “Kevin”]
// Swift can infer [String] so we can also write it as:
Var card Names = [“Jack”, “Leena”, “Kevin”] // inferred as [String]
To add an array, you need to use the subscript println (Card Names [0])
Dictionary: It is similar to a Hash table as in other programming language. A dictionary enables you to store key-value pairs and access the value by providing the key
var cards = [“Jack”: 22, “Leena”: 24, and “Kevin”: 26]
Sets: Set is an unordered collection of unique elements. Sets are like same as Arrays. When we don’t need any order and ensure that each element appears only once in a collection.The main advantage of sets is that we can perform so many operation that array doesn’t. We can perform union, intersection of array using sets.
Set TypeSyntax: The type of a Swift set is represented as Set<Element>, where Element is the type that the set is allowed to store in the program.
Example:
var animals: Set = [“Jack”, “Leena”, “Kevin”] // same as array but ‘Set’ type
What are the properties’ in swift?
In Swift, Properties associate values with a particular class, structure, or enumeration. Stored properties store constant and variable values as part of an instance, whereas computed properties calculate (rather than store) a value. Computed properties are provided by classes, structures, and enumerations. Stored properties are provided only by classes and structures. Stored and computed properties are usually associated with instances of a particular type. However, properties can also be associated with the type itself. Such properties are known as type properties.
What is Enumerations in Swift?
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.
Enumerations in Swift are first-class types in their own right. They adopt many features traditionally supported only by classes, such as computed properties to provide additional information about the enumeration’s current value, and instance methods to provide functionality related to the values the enumeration represents. Enumerations can also define initializers to provide an initial case value; can be extended to expand their functionality beyond their original implementation; and can conform to protocols to provide standard functionality.