Answer these 300+ Swift MCQs and see how sharp is your knowledge of Swift.
Scroll down and let's start!
Which of the following statements are incorrect regarding closures in Apple Swift?
1. In Apple Swift, a closure can capture all the references to variables from the surrounding context in which it is defined, but cannot capture references to constants.
2. A nested function is a closure that has a name but it cannot capture any value from its enclosing function.
3. A global function is a closure that has a name and does not capture any value.
A.
Only 2 and 3
B.
Only1 and 3
C.
Only1 and 2
In Apple Swift, which of the following parameters can be used in a closure expression?
1. Constant parameters
2. Variable parameters
3. Inout parameters
4. Variadic parameters
5. Tuple parameters
A.
Only 1. 2. and 3
B.
Only 1, 2, 3, and 5
C.
Only 2, 3, and 5
D.
Only 1. 2. 3. and 4
E.
All of the given parameters can be used in a closure expression.
A. Only willset observer is called.
B. Only didset observer is called.
C. Neither willset nor didset observer is called.
In Apple Swift, which of the given statements is correct about initializers?
1. Failable and non-failable initializers can be defined with the same name and parameter types
2. No value can be returned by initializers.
3. A failable initializer cannot delegate to a non-failable initializer.
A.
Only1
B.
Only 2
C.
Only 3
What will be the output of the given Apple Swift code?
let a;zUlnt8 = 0b11101111
let sz;lnt8 = 0b00110011
let c=a&b
print(c)
A.
21
B.
25
C.
35
D.
45
A. A Switch statement does not allow empty cases.
B. A Break statement can never be used inside a Switch statement.
C. If only a comment is contained in a Switch case, then it is reported as a compile-time error.
A. Property observers can be added to inherited properties of a class.
B. All the classes in Apple Swift are inherited from a universal base class.
C. Multiple inheritance for classes cannot be supported by Apple Swift.
A. =
B. I=
C. ===
D. =
What will be the output of the following Apple Swift code?
func abc(param1: String) -> lnt[
print(param1)
return param1.characters.count
}
func xyz(param1: String) [
abc(paramI)
}
xyz.("John Smith")
A.
10
B.
John Smith
C.
John Smith10
D.
10John Smith
What will be the output of the following code?
func abc(p: Double...) -> Double {
var sm: Double = O
for number in p[
sm += number
I
return sm I Double{p.count)
I
print(abc(6, 7.25, 16.75))
A.
9.0
B.
9.7
C.
10.0
D.
Code will generate compilation/runtime error.
How many times will the following Apple Swift code print the word "green"?
for p in 21...34[
if p%2==1[
var a = "red"
var b: String?
var c = b ?? a
print( c)
}
else if p%3==2{
let a = "green"
let e = "red"
var f = e ?? a
print(f)
}
else(
var g = "green"
var h: String?
var k = h ?? g
print(k)
}
}
A.
2
B.
4
C.
5
D.
6
Choose True or False.
In Apple Swift, structures are reference types, whereas classes are value types.
A.
True
B.
False
What will be the output of the following code?
class 81 (
func cn10
l
for var a = 9; a >= 1; --a[
for var b = 9; b >= 0; --b[
if b%2==a/2 [
print((b%4).terminator: "")
I
I
print("")
III
let s = a10
s.cn10
A.
311201
11201
20120
B.
1111
1111
00000
C.
13131
13131
02020
A. Variable parameters
B. In-out parameters
C. Variadic parameters
Which of the following statements are valid regarding an assignment operator in Apple Swift?
1. let b=10
2. let (a,b) = (2, 3)
3. if a = b { )
A.
Only1 and 2
B.
Only 2 and 3
C.
Only1 and 3
D.
All the three statements are valid
A. (i)
B. (ii)
C. (iii)
What will be the output of the last line of the given Apple Swift code?
let a=4
print(a&+0)
print(a&-O)
print(a&0)
print(a<<1)
print(a>>1)
print(a<<2)
A.
4
B.
8
C.
16
D.
0
Analyze the following Apple Swift code and select its correct output from the given options.
struct a1 [
var x = 0.0, y = 0.0
}
struct b1 {
var w = 0.0. h = 0.0
}
struct Rt{
var n1 = a1()
var 51 = b1()
var c1: a1 {
getl
let cX = n1.x + (sI.w / 2)
let CY = n1.y -|- (s1.h / 2)
return a1(x: cX. y: cY)
}
set(cc) [
n1.x = cc.x - (s1.w ‘36 4)+2.5
n1.y = my - (sl.h % 4)+2.5
I I I
var rr = Rt(n1: a1(x: 0.0, y: 0.0),
$1: b1(w: 10.0, h: 10.0))
let isc = rr.c1
rr.c1 = a1(x: 16.0, y: 16.0)
print("\(rr.n1.x), \(rr.n1.y)")
A.
10,0,10.0
B.
12.5. 12.5
C.
16.5.16.5
D.
18.5.18.5
Based on your analysis of the following Apple Swift code, identify from the given options the code that will generate compilation error when executed.
func abc
let a1 = a
a = b
b = a1
print("\(a) \(b)")
}
A.
var z =
B.
var p = 5.0
var q = 22/50
abc(&p, &q)
C.
var r = 2.15
var s =19.0/31
abc(&r. 8:5)
D.
Both options a and b
E.
Both options a and c
A. #: (Hash)
B. _ (Underscore)
C. & (Ampersand)
D. $ (Dollar)
What will be the output of the following Apple Swift code?
enum Abc [
case Mark
case John
case Andrew
case Lucy
case June
case Kate
]
enum Class [
case First. Second. Third. Fourth. Fifth. Sixth. Seventh
1
var n1 = Abc.Lucy
n1 = .John
print(n1)
let sp = Class.Sixth
sp = .Third
switch sp {
case .Third:
print("Perrnitted to the cricket ground")
default:
print("Not Permitted to the cricket ground")
]
A.
John
Not Permitted to the cricket ground
B.
(Enum Value)
Not Permitted to the cricket ground
C.
John
Permitted to the cricket ground
D.
Code will give compilation error.
A. Weak references
B. Unowned references
C. None of the above references can be used
A. $
B. ?
C. !
D. @
A. must have at least one designated initializer.
B. must have at least two designated initializers.
C. must have at least three designated initializers.
D. cannot have a designated initializer.
What will be the output of the given Apple Swift code?
var nm = 5.0
class abc[
var x = 0.0
var y: String [
return "\(nm)"
]
func kp0[
println("\(n m)")
1}
let s=abc()
println(s.kp0)
class sd1: abc[
var hB = false
func k1(){
let i = abc();
println("\(i.y)")
let be = sd1()
bc.hB = true
println("\(bc.y)")
println(i.kp())
]}
class Tn: abc[
var nm=15.0
override func kp0[
println(15.0)
]}
let tr = Tn0
tr.kp0
A.
5.0
5.0
B.
15.0
15.0
C.
15.0
5.0
D.
5.0
15.0
What will be the output of the following code?
class a1 {
func cn10
{
for var a = 9; a >=1; --a {
for var b = 9; b >= 0; --b{
if b%2==a/2 [
print((b%4),terminator: "“)
}
}
print("")
}}}
lets = a1()
s.cn1()
A.
1 1 2 01
1 1 2 O 1
2 01 2 0
B.
1 11 11
1 1 1 1 1
O 0 0 0 0
C.
13131
13131
02020
A. Dictionary
B. Lists
C. Both a and b
D. Both b and c
E. Both a and c
Based on your analysis of the above code. find out the output generated by the following lines.
let b1 = abc([9,-7,3,110,4,721)
print("number: \(b1.x), \(b1.y)")
A.
number: 27, 216
B.
number: 216, 27
C.
number: -21, 330
D.
number: 330, -21
A. only one parameter.
B. only two parameters.
C. only three parameters.
D. any number of parameters.
A. Public access
B. Private access
C. Protected access
D. Internal access
A. zero(0)
B. nil
C. NULL
A. They can define type methods.
B. They can override an existing functionality.
C. They can define new nested types, but not subscripts.
D. They can add computed properties.
A. A deinitializer of a class is written with a 'deinit' keyword.
B. There can be at most two deinitializers per class.
C. A deinitializer always takes one parameter.
D. Superclass deinitializers are always called.
A. Initializers can be defined by structures to set up their starting state.
B. Methods can be defined by structures to provide functionality.
C. Type casting enables us to verify and interpret the type of a structure instance at runtime.
D. Reference counting permits more than one reference to a structure instance.
A. Global constants
B. Local constants
C. Global variables
D. Local variables
A. ?:
B. &&
C. &’
D. ??
A. In the Apple Swift language. information about a property is defined in multiple locations.
B. An Apple Swift property does not have a corresponding instance variable.
C. Computed properties can be defined by enumerations in the Apple Swift language.
D. None of the above.
A. They can be used as a return type in a function.
B. They cannot support multiple inheritance.
C. They cannot be used as the type of a property.
D. They can be used as the type of items in a dictionary.
A. 8% 2 returns 0
B. 16 % 5 returns 1.0
C. 23 % 7.5 returns 0.5
D. -9 96 4 returns 1
A. Assignment operator (=)
B. Ternary conditional operator (?:)
C. Right bit shift and assign (>>=)
D. Add and assign (+=)
What is the name of the Xcode generated header file used to import Swift classes into an Objective-C Class given a product module named Example?
A. ExampleSwift.h
B. Example.Swift.h
C. Example+Swift.h
D. Example-Swift.h
What does a retainCount represent in ARC?
A. The current number of strong references to an object.
B. The current number of instances of an object.
C. The total number of objects currently being retained in memory.
D. The total number of times an object has been allocated.
Which one of the below functions definitions is wrong considering Swift language?
A. func haveChar(#string: String, character: Character) -> (Bool)
B. func mean(numbers: Double...) -> Double
C. func minMax(array: [Int]) -> (min: Int, max: Int)?
D. func minMax(array: [Int]) -> (min: Int?, max: Int?)
Which of these is a valid syntax for iterating through the keys and values of a dictionary?
let dictionary = [keyOne : valueOne, keyTwo : valueTwo]
A. for (key, value) in dictionary { println("Key: (key) Value: (value)") }
B. for (key, value) in enumerate(dictionary) { println("Key: (key) Value: (value)") }
C. for (key, value) in (dictionary.keys, dictionary.values) { println("Key: (key) Value: (value)") }
D. for (key, value) in dictionary.enumerate() { println("Key: (key) Value: (value)") }
What is the name of the Swift language feature that Objective-C Blocks are translated into?
A. Lambda
B. Callback
C. Closure
D. Selector
Which one creates a dictionary with a key type of Integer and value of String?
A. var dict:[Int: String] = ["one":1]
B. var dict: [Int: String] = [1:"one"]
C. var dict: [String: Int] = [1:"one"]
D. var dict = ["one":1]
Which of these is an appropriate syntax for dispatching a heavy operation to a background thread?
A. dispatch_async(DISPATCH_QUEUE_PRIORITY_BACKGROUND), { self.heavyOperation() })
B. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIO RITY_BACKGROUND, 0), { self.heavyOperation() })
C. DISPATCH_QUEUE_PRIORITY_BACKGROUND({ self.heavyOperation() })
D. dispatch_async({ self.heavyOperation() })
What is the name of the deinitializer in a Class declaration?
A. deinit
B. dealloc
C. release
Which of these is an appropriate syntax for declaring a function that takes an argument of a generic type?
A. func genericFunction(argument: T<Generic>) { }
B. func genericFunction<T>(argument) { }
C. generic func genericFunction(argument: T) { }
D. func genericFunction<T>(argument: T) { }
Which of these is not a valid property declaration in Swift?
A. final let x = 0
B. final lazy let x = 0
C. final lazy var x = 0
D. final var x = 0
Which is the wrong definition of a protocol in Swift?
A. protocol SomeProtocol { var first: Int{ get } }
B. protocol SomeProtocol { var first: Int{ set } }
C. protocol SomeProtocol { var first: Int { get set } }
D. protocol SomeProtocol { var first: Int { get set } var second: Int { get } }
Which of the following structures has both computed and stored properties?
A. struct Rect { var origin = CGPointZero var center: CGPoint { get { // } set { // } } }
B. struct Rect { var center: CGPoint { get { // } set { // } } }
C. struct Rect { let origin = CGPointZero }
D. struct Rect { var origin = CGPointZero var center: CGPointMake(0,0) }
All Swift classes must inherit from which root class?
A. Swift classes do not require a root class.
B. NSObject
C. @ObjC
D. Root
Which keyword is used on a function inside an Enumeration to indicate that the function will modify 'self'?
A. modifier
B. mutating
C. mutable
D. mod
E. mut
Which of these is a valid definition of a generic function that incorporates inout parameters in Swift?
A. func swap<T>(inout a: T, inout b: T) { let temp = a a = b b = temp }
B. func swap<U,T>(inout a: U, inout b: T) { let temp = a a = b b = temp }
C. func swap<U,T>( a: U, b: T) { let temp = a a = b b = temp }
D. func swap<T>( a: T, b: T) { let temp = a a = b b = temp }
Which of the following statements could be used to determine if a given variable is of String type?
A. if String.hierarchy(unknownVariable) { }
B. if unknownVariable is String { }
C. if unkownVariable: String { }
D. if (String)unknownVariable { }
Which of these could be an appropriate protocol declaration in Swift?
A. @objc protocol someProtocal { optional var first: Int { get } }
B. @objc protocol someProtocal { optional var first: Int { set } }
C. protocol someProtocal { optional var first: Int { get } }
D. protocol someProtocal { var first: Int { set } }
In context of a Swift subscript, which of the following is correct?
A. struct MyStruct { var myStr = [String]() subscript (index : Int) -> String{ get{ return myStr[index] } set{ myStr[index] = newValue } } }
B. struct MyStruct { var myStr = [String]() subscript (index : Int) -> Int{ get{ return myStr[index] } set(newValue){ myStr[index] = newValue } } }
C. struct MyStruct { var myStr = [String]() subscript (index : Int) -> String{ get(){ return myStr[index] } set(newValue){ myStr[index] = newValue } } }
D. struct MyStruct { var myStr = [String] subscript (index : Int) -> String{ get(){ return myStr[index] } set(newValue){ myStr[index] = newValue } } }
What is used to import Objective-C files into Swift?
A. Objective-C classes are automatically imported.
B. Objective-C classes are imported in the Swift file using the class.
C. Objective-C classes are imported via a Bridging Header.
D. Objective-C classes import themselves by declare @SwiftImportable.
What keyword is used to indicate a custom operator that will appear in between two targets, similar to the addition operator in this example?
var sum = 10 + 10
A. @inter
B. between
C. infix
D. @center
Which is correct regarding Swift enumeration members when they are defined?
A. Members are assigned a default integer value.
B. Members are assigned a random default integer value.
C. Members are not assigned default integer values.
What type of object are Swift Structures?
A. Reference Type
B. Memory Type
C. Abstract Type
D. Value Type
Given that we have defined myChar like so :
let myChar: Character = "b" Which code segment can be considered a complete Switch statement and will run without any error?
A. switch myChar { case "a","A": println("The letter A") case "b","B": println("The letter A") }
B. switch myChar { case "a": println("The letter A") }
C. switch myChar { case "a": case "A": println("The letter A") default: println("Not the letter A") }
D. switch myChar { case "a","A": println("The letter A") default: println("Not the letter A") }
Can enumeration type have methods?
A. Enumerations can have methods associate with them.
B. Enumerations can have only member values.
Which of the following declares a mutable array in Swift?
A. var x = [Int]
B. let x = [Int]
C. var x = [Int]()
D. let x = [Int]()
Which keyword is used in Swift when we want a property of a class to initialize when it is accessed for the first time?
A. let
B. var
C. const
D. lazy
Which is used for down casting?
A. as!
B. is
C. is?
D. as?
Which of the following types can be used use as raw value types for an enumeration?
A. Bool
B. Array
C. Int, String, Float
D. Dictionary
Which keyword do you use to declare enumeration?
A. var
B. enum
C. struct
D. case
When declaring an enumeration, multiple member values can appear on a single line, separated by which punctuation mark?
A. Semi-colon
B. Colon
C. Comma
D. Slash
E. Point
How do closures capture references to variables by default ?
A. By weak reference
B. By strong reference
C. By unowned reference
D. By copy
What is used in Swift to represent any kind of object?
A. Ob
B. id
C. AnyObject
D. Nothing
What is the name of the Objective-C Bridging Header given a product module named Example?
A. Example-Bridging-Swift.h
B. Example-Swift.h
C. Example-Bridging-ObjectiveC.h
D. Example-Bridging-Header.h
What is the type name that represents a character in Swift?
A. Character
B. Char
C. String
D. NSString
What is a muting instance method in Swift?
A. When there is "muting" keyword in front of extension.
B. When extension can add new types to existing classes.
C. When instance method without extension can modify itself.
D. A method that modifies self.
Swift Extensions are similar to categories in Objective-C except:
A. Swift extension might have a specific name
B. Swift extension doesn’t functionality to previously defined type.
C. Swift can override method from original type.
D. Swift extensions are not named.
Considering the following code, which statement is Correct:
let array1 = ["A", "B", "C"] var array2 = array1 array2.append("D")
A. array1 will be copied to array2 after the assignment
B. Reference count of array1 won't change after the assignment
C. array1 will change to [A, B, C, D] after appending D
D. Code will not compile, can not assign constant array1 to variable array2
How could we create a subclass of the Structure, CGRect?
A. struct MyRect: CGRect {}
B. struct CGRect(MyRect) {}
C. You can not subclass a Structure
D. struct MyRect extends CGRect {}
Which is correct regarding optional form of the type cast operator (as?)?
A. It will trigger a runtime error if you try to downcast to an incorrect class type.
B. This is used when you are sure that the downcast will always succeed
C. Return value will be nil if the downcast was not possible
How could one declare a Swift Array type that can store any type of class object?
A. var arr: [id] = [ ]
B. var arr: [AnyObject] = [ ]
C. [AnyObject] arr = [ ]
D. var arr = NSArray<AnyObject>()
How could we cast the following array into an NSArray that accesses the NSArray method:
componentsJoinedByString() < let arr = ["1", "2", "3"]
A. arr.toNSArray.componentsJoinedByString(",")
B. NSArray(arr).componentsJoinedByString(",")
C. (arr as NSArray).componentsJoinedByString(",")
D. (arr bridge NSArray).componentsJoinedByString(",")
What set of keywords is most commonly used to iterate over a collections of items?
A. for each
B. switch case
C. do while
D. for in
How can we use optional binding to determine if the variable string is not nil?
A. if let str = string {…}
B. if string {…}
C. if string as String {…}
D. if let string {…}
Choose the answer that declares an optional closure.
A. var closureName: (parameterTypes) -> (returnType)
B. typealias closureType = (parameterTypes) -> (returnType)
C. var closureName: ((parameterTypes) -> (returnType))
D. let closureName: closureType = { … }
Let’s assume "numbers" is an array of unsorted integers. Which of these could be used to sort numbers?
A. numbers.sort({$0, $1 in $0 > $1})
B. numbers.sort({s1 > s2})
C. numbers.sort({$0 > $1})
D. numbers.sort(){s1 > s2}
How could you call the following function that takes a closure as an argument using trailing closure syntax: ()) { // function body goes here }>
A. funcWithClosure ({ //closure’s body goes here })
B. funk funcWithClosure ({ //closure’s body goes here })
C. funcWithClosure() { //closure’s body goes here }
D. funcWithClosure { //closure’s body goes here )
How could the following closure be rewritten to use shorthand arguments? s2 } ) >
A. reversed = sorted(names, { $0 ,$1 in $0 > $1 } )
B. reversed = sorted(names, { $0 > $1 } )
C. reversed = sorted(names, { $0 ,$1 } )
D. reversed = sorted( { $0 > $1 } )
What is a trailing closure?
A. A closure expression that is called directly after another closure expression
B. A closure expression that is written outside of (and after) the parentheses of the function call it supports.
C. A closure expression that is declared within the scope of another closure expression.
D. A closure expression that is declared at the property of an object.
Which of the following statements is true regarding Swift closures and functions?
A. Functions and Closures are not related
B. A Function is a Closure declared within the scope of a Class
C. A Function is a named Closure
D. Closures can’t be used as arguments, Functions can
What are the available arithmetic overflow operators in Swift?
A. op+,op-,op*,op/,op%
B. &+,&-,&*,&/,&%
C. +,-,*,/,%
D. &, |, &&, ||
What specifies custom infix operator?
A. it is a binary operator, taking a left and right hand argument
B. it is a unary operator written before its operand
C. it is a unary operator written after its operand
D. it is a reserved word that must be preceded with **
Which of following statements about functions is wrong?
A. In-out parameters might have a default value
B. Function might have multiple return values
C. Function might not have return values
D. Function names might be the same with another but at least one parameter should be different
In the below text, what type of return does the function ‘area’ give? Class Square: NamedShape { var sideLength: Double func area() -> Double { return sideLength*sideLength } }
A. Int
B. the area of a square
C. Double
D. area
In the below text, what is the class name? Class Square: NamedShape { var sideLength: Double func area() -> Double { return sideLength*sideLength } }
A. NamedShape
B. Square
C. class
D. Double
E. sideLength
In the below text, what is the name of the class’s only method? Class Square: NamedShape { var sideLength: Double func area() -> Double { return sideLength*sideLength } }
A. sideLength
B. area
C. Square
D. NamedShape
E. Double
What aspect of iOS development requires the use of NSOperation and/or Grand Central Dispatch (GCD)?
A. Multithreading
B. serial task
C. None
D. Message Sending
Which of following expressions can be used to rewrite the following UITableView instantiation in Swift UITableView *myTableView = [[UITableView alloc] initWithFrame: CGRectZero style: UITableViewStyleGrouped];
A. let myTableView: UITableView = new UITableView(frame: CGRectZero, style: .Grouped);
B. let myTableView: UITableView = UITableView.alloc().init(frame: CGRectZero, style: .Grouped);
C. let myTableView: UITableView = UITableView(frame: CGRectZero, style: .Grouped);
D. let myTableView: UITableView = UITableView(frame: CGRectZero, style: UITableViewStyleGrouped)
What will happen if you assign a value to a property within its own didSet observer?
A. didSet will be called again
B. It will create an infinite loop
C. The property will take on that value
D. Code will not compile
Which of the following is correct to cube Integer?
A. extension Int { mutating func cube () { self = selfselfself } }
B. extension Int { mutating func cube () { return selfselfself } }
C. extension Int { func cube () { self = selfselfself } }
D. extension Int { func cube () { return selfselfself } }
In what queue should all UI code be handled?
A. BackgroundQueue
B. UIQueue
C. Any Queue
D. MainQueue