Ans: Swift is a programming language and system for creating applications for iOS and OS X. It is an innovative programming language for Cocoa and Cocoa Touch.
Ans: Variables and constants must be declared before they are used. You announce constants with the let keyword and variables with the var keyword. Both variables and dictionaries are described using brackets. For example,
Var myTectra = “This is myTectra”
Let ksomeconstant = 30
Ans: Swift program deploys the application in a Tomcat installation by default. The deploy script bundles the client code into JavaScript, gathers all the server side classes required and packages them into file Hello.war. This file together with a GWT jar and a Swift runtime jar is copied into the Tomcat installation. If CATALINA_HOME is not set, these files require to be copied manually.
Ans: Difference between ‘C’ and ‘Swift’ language is that
Swift | Objective-C |
·In a swift, the variable and constants are declared before their use
·You have to use “let” keyword for constant and “var” keyword for variable ·There is no need to end code with semi-colon ·Concatenating strings is easy in swift and allows to make a new string from a mix of constants, literals, variables, as well as expressions ·Swift does not require to create a separate interface like Objective C. You can define classes in a single file (.swift) ·Swift enables you to define methods in class, structure or enumeration ·In Swift, you use “ +=” Operator to add an item |
·In objective C, you have to declare variable as NSString and constant as int
·In objective C, variable is declared as “ and constant as “ ·The code ends with semi-colon ·In objective C, you have to choose between NSMutableString and NSString for string to be modified. ·For classes, you create separate interface (.h) and implementation (.m) files for classes ·Objective does not allow this ·In C, you use “addObject”: method of NSMutable array to append a new item to an array |
Ans: 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.
Ans: Floating numbers are numbers with a fractional component, like 3.25169 and -238.21. Floating point types can represent a wider range of values than integer types. There are two signed floating point number
Ans: Multiple line comment can be written as forward-slash followed by an asterisk (/*) and end with an asterisk followed by a forward slash (*/).
Ans: 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. It is written as
deinit {
// perform the deinitialization
}
Ans: In Swift, collection types come in two varieties Array and Dictionary
Example for single type array is,
Var cardName : [String] = [ “Robert” , “Lisa” , “Kevin”]
// Swift can infer [String] so we can also write it as:
Var cardNames = [ “Robert”, “Lisa”, “Kevin”] // inferred as [String]
To add an array you need to use the subscript println(CardNames[0])
var cards = [ “Robert”: 22, “Lisa” : 24, and “Kevin”: 26]
Ans: Control transfer statements used in Swift includes
Ans: Optional chaining is a process of querying and calling properties. Multiple queries can be chained together, and if any link in the chain is nil then, the entire chain fails.
Ans: In Swift the classes are not inherited from the base class and the classes that you define without specifying its superclass, automatically becomes the base-class.
Ans: 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.
Ans:
Ans: 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? = “John"if optionalName != nil { print(“Your name is \(optionalName!)”)}
Ans: To provide a default value for a variable.
let missingName : String? = nillet realName : String? = “John Doe"let existentName : String = missingName ?? realName
Ans: 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. There is a method for avoiding forced unwrapping which we will cover below.
Ans: The let keyword is used to declare constants while var is used for declaring variables.
let someConstant = 10var someVariable : String
Here, we used the : string to explicitly declare that someVariable will hold a string. In practice, it's rarely necessary — especially if the variable is given an initial value — as Swift will infer the type for you. It is a compile-time error trying to use a variable declared as a constant through let and later modifying that variable.
Ans: 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
Ans: 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.
Ans: Optional bindings or chaining come in handy with properties that have been declared as optional. Consider this example:
class Student { var courses : [Course]?}let student = Student()
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 is a term used when you assign temporary variables from optionals 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.
if let courses = student.courses { print("Yep, courses we have")}
The code above will continue since we have not initialized the courses array yet. Simply adding:
init() { courses = [Course]() }
Will then print out "Yep, courses we have."
Ans: The external parameter precedes the local parameter name.
func yourFunction(externalParameterName localParameterName :Type, ...) { ... }
A concrete example of this would be:
func sendMessage(from name1 :String, to name2 :String) { print("Sending message from \(name1) to \(name2)") }
Ans: If you need to perform additional cleanup of your custom classes, it's possible to define a block called deinit. The syntax is the following:
deinit { //Your statements for cleanup here }
Typically, this type of block is used when you have opened files or external connections and want to close them before your class is deallocated.
Ans: 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 errortry canThrowErrors() //Or specify it as an optionallet maybe = try? canThrowErrors()</pre>What is a guard statement in Swift?
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}
Ans: var array1 = [1, 2, 3, 4, 5]
var array2 = array1
array2.append(6)
var len = array1.count
Ans: The len variable is equal to 5, meaning that array1 has 5 elements, whereas array2 has 6 elements:
array1 = [1, 2, 3, 4, 5]
array2 = [1, 2, 3, 4, 5, 6]
When array1 is assigned to array2, a copy of array1 is actually created and assigned.
The reason is that swift arrays are value types (implemented as structs) and not reference types (i.e. classes). When a value type is assigned to a variable, passed as argument to a function or method, or otherwise moved around, a copy of it is actually created and assigned or passed. Note that swift dictionaries are also value types, implemented as structs.
Value types in swift are:
let op1: Int = 1
let op2: UInt = 2
let op3: Double = 3.34
var result = op1 + op2 + op3
Ans: Swift doesn’t define any implicit cast between data types, even if they are conceptually almost identical (like UInt and Int).
To fix the error, rather than casting, an explicit conversion is required. In the sample code, all expression operands must be converted to a common same type, which in this case is Double:
var result = Double(op1) + Double(op2) + op3
Q29. The String struct doesn’t provide a count or length property or method to count the number of characters it contains. Instead a global countElements<T>() function is available. When applied to strings, what’s the complexity of the countElements function:
and why?
Ans: Swift strings support extended grapheme clusters. Each character stored in a string is a sequence of one or more unicode scalars that, when combined, produce a single human readable character. Since different characters can require different amounts of memory, and considering that an extreme grapheme cluster must be accessed sequentially in order to determine which character it represents, it’s not possible to know the number of characters contained in a string upfront, without traversing the entire string. For that reason, the complexity of the countElements function is O(n).
Ans: Raw values are used to associate constant (literal) values to enum cases. The value type is part of the enum type, and each enum case must specify a unique raw value (duplicate values are not allowed).
The following example shows an enum with raw values of type Int:
enum IntEnum : Int {
case ONE = 1
case TWO = 2
case THREE = 3
}
An enum value can be converted to its raw value by using the rawValue property:
var enumVar: IntEnum = IntEnum.TWO
var rawValue: Int = enumVar.rawValue
A raw value can be converted to an enum instance by using a dedicated initializer:
var enumVar: IntEnum? = IntEnum(rawValue: 1)
Associated values are used to associate arbitrary data to a specific enum case. Each enum case can have zero or more associated values, declared as a tuple in the case definition:
enum AssociatedEnum {
case EMPTY
case WITH_INT(value: Int)
case WITH_TUPLE(value: Int, text: String, data: [Float])
}
Whereas the type(s) associated to a case are part of the enum declaration, the associated value(s) are instance specific, meaning that an enum case can have different associated values for different enum instances.
struct IntStack {
var items = [Int]()
func add(x: Int) {
items.append(x) // Compile time error here.
}
}
Ans: 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!
}
}
var myswiftArray = myMutableArray as NSArray as! [String]
Ans: We can convert the SwiftArray to a MutableArray by using the following code.
let myArray: NSArray = ["iOS","Android","PHP"]
var myMutableArray = NSMutableArray(array:myArray)
print(myMutableArray)
Ans:
let SwiftCharacterArray: [Character] = ["a", "b", "c", "d"]
let SwiftString = String(characterArray)
print(SwiftString)
Ans:
let SwiftStringArray = ["cocos2d", "cocos2d-x", "UIKit"]
let SwiftCharacterArray = SwiftStringArray.flatMap { String.CharacterView($0) }
let SwiftString = String(SwiftCharacterArray)
print(SwiftString)
Ans:
let SwiftStringsArray = ["iPhone", "iPad", "iPod"]
let MySwiftString = SwiftStringsArray.joinWithSeparator(",")
print(MySwiftString)
Ans:
let Ustring : String = "iOS Developer Questions"
let characters = Array(Ustring.characters)
print(characters)