TUTORIALS

Swift Multiple Choice Questions (MCQs)

1 .
Topic:  Basics
Question:
Choose all correct statements. S1: Swift was developed by Apple Inc S2: Swift has file name extension as .swift S3: Swift is an alternative to the Objective-C language
A
S1 and S2
B
S1 and S3
C
S2 and S3
D
S1, S2 and S3
Answer: D
Explanation: Swift is a powerful and intuitive programming language for macOS, iOS and beyond by Apple engineering culture and the diverse contributions from its open-source community.Swift is an alternative to the Objective-C language that employs modern programming-language theory concepts.SWIFT files store source code written Swift programming language with an extension .swift.
2 .
Topic:  Basics
Question:
Which among the following is not an Swift feature?
A
Tuples
B
Built in error handling
C
Generics
D
None of the above
Answer: D
Explanation: Swift supports tuples, arrays, enums, structs, sets, dictionary, generics, built in error handling, loops, protocols, type casting and optionSet
3 .
Topic:  Basics
Question:
What is the file extension for Swift programs?
A
.s
B
.sw
C
.swift
D
.sp
Answer: C
Explanation: SWIFT files store source code written Swift programming language with an extension .swift.
4 .
Topic:  Basics
Question:
How to compile and run a script in one step?
A
$ swift filename.swift
B
$ swiftc filename
C
$ swiftc filename.swift
D
$ swift filename.s
Answer: A
Explanation: Scenario 1: To compile and run a script in one step, use swift from the terminal $ swift filename.swift Scenario 2: To compile and run separately in different steps we can use swiftc $ swiftc filename.swift $ ./filename
5 .
Topic:  Basics
Question:
How to compile a script?
A
$ swift filename.swift
B
$ swiftc filename
C
$ swiftc filename.swift
D
$ swift filename.s
Answer: C
Explanation: Scenario 1: To compile and run a script in one step, use swift from the terminal $ swift filename.swift Scenario 2: To compile and run separately in different steps we can use swiftc $ swiftc filename.swift $ ./filename
6 .
Topic:  Basics
Question:
Which command is used to get the current version of swift?
A
$ swift -version
B
$ swift --version
C
$ swift --v
D
$ swift --currentversion
Answer: B
Explanation: To get the current version of Swift, run thefollowing command: $ swift --version
7 .
Topic:  Variables and Properties
Question:
Which is a valid variable name in Swift?
A
Has unicode characters
B
Has whitespace
C
Has Mathematical Symbols
D
Has arrows
Answer: A
Explanation: Variable names can have letters, numbers, unicode characters. But they cant have whitespace characters, mathematical symbols, arrows, drawing characters.
8 .
Topic:  Variables and Properties
Question:
Which among the following is a characteristic of Lazy Stored Procedures?
A
Have values that are not calculated until first accessed
B
lazy property is declared with lazy
C
Lazy stored properties must be declared with var
D
All of the above
Answer: D
Explanation: Lazy stored properties have values that are not calculated until first accessed.So, prefix it with the lazy keyword so it will be "excluded" from the initialization process and it's default value will be assigned on-demand. It must always be a variable. Lazy stored procedures helps in optimizing the memory and CPU usage and increases readability of the code. It can only be used on structs and classes. The limitation of using this lazy stored procedures is that it is not thread safe as “lazy"modifiercan be accessed simultaneously by multiple threads.
9 .
Topic:  Variables and Properties
Question:
Choose the correct Statements: S1: computed properties are built with a getter and a setter. S2: computed properties are always variables and cant be constants. S3: computed properties store something on an object and affect its memory.
A
S1 and S2
B
S1 and S3
C
S2 and S3
D
S1, S2 and S3
Answer: A
Explanation: Computed properties of swift performs necessary computation each time it is accessed and returns a value rather than storing it. Hence their value can change each time it is called. They are always variables which are build with getter and setter methods using get and set keywords. Default value of the variable should not be assigned. It can be defined by providing the variable name and declare irs type explicity.
10 .
Topic:  Variables and Properties
Question:
Which is not a property of type properties in Swift?
A
Type properties are properties on the type itself, not on the instance
B
type property is declared with static keyword
C
type property can be both stored or computed properties
D
type property is declared with type keyword
Answer: D
Explanation: Type properties are the static properties which are defined on the type itself instead of any instance. The properties can be accessed by type name without creating a new object. It can be both stored and computed properties.Type Properties are defined with the keyword static if the type property is not meant to be overridden by a subclass and use the keyword class if it can be overridden by subclass.
11 .
Topic:  Numbers
Question:
The built-in numeric types in Swift
A
Int4
B
Integer
C
UInt
D
Float16
Answer: C
Explanation: The basic data types supported by swift are signed Int, unsigned UInt,and Fixed-size signed integers Int8, Int16, Int32, Int64, and unsigned integers UInt8, UInt16, UInt32, UInt64.Float(Float/Float32), Double(Float64/Double), Float80, Bool, String, Character, Optional and Tuples.
12 .
Topic:  Variables and Properties
Question:
Which symbol is used to separate digits in numeric literals
A
Underscore (_)
B
Dash(-)
C
Dot(.)
D
Rounded Brackets()
Answer: A
Explanation: Underscores (_) may be used to separate digits in numeric literals. Leading zeros are ignored.
13 .
Topic:  Numbers
Question:
Choose the correct evaluated statement
A
round(-3.500) = -3
B
ceil(-3.999) = -3
C
floor(-3.001) = -3
D
Int(-3.999) = -4
Answer: B
Explanation: round(_:) Rounds the value to an integral value using the specified rounding rule. ceil(_:) Rounds any number with a decimal value up to the next larger whole number. floor(_:) Rounds any number with a decimal value down to the next smaller whole number. Int: Converts a Double to an Int, dropping any decimal value.
14 .
Topic:  Variables and Properties
Question:
The supported architecture for round, ceil and floor in Swift is/are
A
32 bit architecture
B
64 bit architecture
C
Both 32 and 64 bit architecture
D
None of the above
Answer: C
Explanation: Both 32 and 64 bit architecture supports round,ceil and floor funcctions
15 .
Topic:  Numbers
Question:
What is the general form of Random number generation in Swift?
A
let number = min + arc4random_uniform(max + min + 1)
B
let number = min + arc4random_uniform(max , min + 1)
C
let number = min + arc4random_uniform(max - min - 1)
D
let number = min + arc4random_uniform(max - min + 1)
Answer: D
Explanation: There are three typical functions for random numbers: arc4random() returns a random number between zero and (2^32 or UInt32.max) – 1 arc4random_uniform(n) returns a random number between zero and the (parameter minus one). drand48() returns a random Double between 0.0 and 1.0 let number = min + arc4random_uniform(max - min + 1) where number, max, and min are UInt32. But these are not recommended for cryptography or security purposes as they appear random but numbers from these functions are generated with a mathematical formula changes of reptpitions are possible.
16 .
Topic:  Numbers
Question:
Which among the following throws runtime error in Swift?
A
Int8(-128)
B
Int8(128)
C
Int(-0.1)
D
Int8(-2)
Answer: B
Explanation: Integer initializers produce a runtime error if the value overflows or underflows and Float-to-integer conversion rounds values towards zero.
17 .
Topic:  Strings and Character
Question:
Which special character doesn’t require escape sequence in order to use them in string literals?
A
the null character
B
a vertical tab
C
a double quote
D
dollar character
Answer: D
Explanation: Certain characters require a special escape sequence to use them in string literals like the null character, a plain backslash,a tab character, a vertical tab, a carriage return , a line feed, double and single codes.
18 .
Topic:  Strings and Character
Question:
Which among the following is not true with respect to concatenation of strings in Swift?
A
Concatenate strings with the + operator to produce a new string
B
Can append a single character to a mutable String
C
Can append multiple characters to a mutable String
D
concatenation of strings is possible using += only not by using append method.
Answer: D
Explanation: In swift, we can concatenate strings with the + operator to produce a new string.To a mutable String , we can append single character and multiple characters using += operator or an append method
19 .
Topic:  Strings and Character
Question:
Which statements evaluates to true while checking the equal strings in swift?
A
"abc" == "def"
B
"abc" == "ABC"
C
"abc" == "abc"
D
"abc" ==="def"
Answer: C
Explanation: To check two strings are equal we can use == . Comparison is case senstive.
20 .
Topic:  Strings and Character
Question:
Which method is used to check for prefix in Swift?
A
hasPrefix
B
isPrefix
C
isPart
D
has
Answer: A
Explanation: To check whether a string starts with another string we can use hasPrefix and to check whether a string ends with another string, hasSuffix can be used. Example for prefix: "attitude".hasPrefix("at") // true Example for suffix: "Swift Programming".hasSuffix("ing") // true
21 .
Topic:  Strings and Character
Question:
Which method is used in String Iteration in Swift?
A
index(after:)
B
index.successor()
C
index.next()
D
index.forward()
Answer: B
Explanation: In Swift 3, String indexes no longer have successor(), predecessor() but in versions <3.0 successor and precessor are used. index.successor() cant be called on empty strings hence empty check operation should be first
NOTE: For Version<3.0
22 .
Topic:  Strings and Character
Question:
Which among the following operations are valid with respect to Strings in Swift? let string = "Super Power" S1: string[2] S2: string.characters[2]
A
S1 only
B
S2 only
C
Both S1 and S2
D
Neither S1 nor S2
Answer: D
Explanation: In swift, it is not possible to access the character of a string using its nor .characters[index]index as the index is an object type and an Int
23 .
Topic:  Strings and Character
Question:
Choose the correct expression
A
Int("123") returns error
B
Int("hello") returns nil
C
Int("10", radix: 2) returns 10 of Int type
D
Double("hello") returns hello
Answer: B
Explanation: Int("hello") and Double("hello") returns nil as it reurns an Optional value.
24 .
Topic:  Strings and Character
Question:
How to conver the given String to uppercase in Swift? Given let string = "HhEeLlLlOo"
A
string.uppercased()
B
string.upper()
C
string.uppercase()
D
string.toUppercase()
Answer: A
Explanation: To make all chacters in s atring to upper case we can use uppercased() and to make all lowercase we can use lowercased() for version 3.0. In version 2.2 uppercaseString() and lowercaseString() methods are used
NOTE: For Version 3.0
25 .
Topic:  Strings and Character
Question:
Which are the Boolean Logical Operators used in Swift?
A
OR(||)
B
XOR(^^)
C
negate(~)
D
AND(&)
Answer: A
Explanation: Bool is a Boolean type with two possible values: true and false. Following are the boolean logical operators supported by swift: The OR (||) operator returns true if one of its two operands evaluates to true, otherwise it returns false. The AND (&&) operator returns true only if both operands evaluate to be true The XOR (^) operator returns true if one and only one of the two operands evaluates to true The prefix ! operator is used to negate a boolean value.
26 .
Topic:  Strings and Character
Question:
Which operator is used to negate a Bool in Swift?
A
!
B
~
C
NOT
D
!=
Answer: A
Explanation: Following are the boolean logical operators supported by swift: The OR (||) operator returns true if one of its two operands evaluates to true, otherwise it returns false. The AND (&&) operator returns true only if both operands evaluate to be true The XOR (^) operator returns true if one and only one of the two operands evaluates to true The prefix ! operator is used to negate a boolean value.
27 .
Topic:  Arrays
Question:
Which type are arrays in Swift?
A
object
B
value
C
string
D
only immutable
Answer: B
Explanation: Array is an ordered, random-access collection type which hold elements of a single type,varying from integers, strings to classes.Array is a value typed. Its mutability is defined as mutable if mut keyword is used and immutable if let keyword is used.
28 .
Topic:  Arrays
Question:
Which among the following array declarations is invalid?
A
var arrayOfStrings: [String] = []
B
let arrayOfUInt8s: [UInt8] = [2, 6, 8]
C
var arrayOfStrings = Array<String>()
D
var arrayOfStrings = [String]
Answer: D
Explanation: Arrays can be declared in many ways: var arrayOfStrings: [String] = [] let arrayOfUInt8s: [UInt8] = [2, 6, 8] var arrayOfStrings = Array<String>()
29 .
Topic:  Arrays
Question:
Which of the following are supported by swift with respect to arrays?
A
Empty arrays
B
Arrays with repeated values
C
Multi-dimensional arrays
D
All of the above
Answer: D
Explanation: Empty arrays, Arrays with repeated values,Multi-dimensional arrays, creating arrays from other sequences are supported by Swift
30 .
Topic:  Arrays
Question:
How to define an array with repeated values?
A
let arrayOfStrings = Array(repeat: "Swift", 4)
B
let arrayOfStrings = Array(repeat: "Swift",count: 4)
C
let arrayOfStrings = Array(repeating: "Swift",count: 4)
D
repeated values not supported
Answer: C
Explanation: let arrayOfStrings = Array(repeating: "Swift",count: 4) is used to define an array with repeated values.
31 .
Topic:  Arrays
Question:
Which method is used to extract values of a given type from an Array in Swift?
A
flatMap
B
extractMap
C
getValues
D
fetchValues
Answer: A
Explanation: flatMap in swift returns an array containing the concatenated results of calling the given transformation with each element of this sequence. It works just like map, but also flattens the resulting “array of arrays” into just a single array.
32 .
Topic:  Arrays
Question:
How to filter out nil from an Array transformation?
A
extractMap
B
filterMap
C
valueMap
D
flatMap
Answer: D
Explanation: flatMap in swift returns an array containing the concatenated results of calling the given transformation with each element of this sequence. It works just like map, but also flattens the resulting “array of arrays” into just a single array. Also flapMap can be used to filter out nil from an Array transformation.
33 .
Topic:  Arrays
Question:
In the array color, how to remove "green" without knowing its index var color = ["red", "blue", "green", "yellow", "black"]
A
color.remove("green")
B
color.remove(at:2)
C
color.remove("2")
D
color.filter("green")
Answer: A
Explanation: To remove an element from an array when it's index is known, it can be easily removed using remove(at:) function. But when index is not known when we can specify the element directly in remove function
NOTE: Swift 3
34 .
Topic:  Arrays
Question:
Which among the following is false with respect to map in Swift?
A
used for transforming an array of A to array of B
B
Changes the type of array
C
iterates through array
D
populates a new array with the transformed elements
Answer: B
Explanation: map(_:) can be used to transform the elements of an Array by iterating through array and populating a new array with the transformed elements
35 .
Topic:  Arrays
Question:
Which method is used to compare two arrays in swift?
A
compare
B
check
C
zip
D
reduce
Answer: C
Explanation: Zip function can be used to compare two arrays. It accepts two parameters of type SequenceType and returns a Zip2Sequence where each element contains a value from the first sequence and one from the second sequence
36 .
Topic:  Arrays
Question:
Which of following array operations supported by Swift?
A
Sorting an Array
B
Grouping Array values
C
Finding the minimum or maximum element with a custom ordering
D
All of the above
Answer: D
Explanation: Arrays can be sorted, grouped, modified,compared, filtered, accessed, subscript with arange, flattened, combined and transformed and also find maximum and minimum value of an array
37 .
Topic:  Arrays
Question:
Which of following methods are valid in Array operations in Swift? Given: var helloArray:[Int] = [1,2,3,4,5] S1: helloArray.indexOf(2) S2: helloArray.first S3: helloArray.min() S4: helloArray.append(6)
A
S1,S2 and S3
B
S1,S3 and S4
C
S2,S2 and S4
D
S1,S2,S3 and S4
Answer: D
Explanation: indexOf can be used to access the element of an array at the index specified, first is used to return the first element of an array and min() function returns the minimum value of an array
38 .
Topic:  Tuples
Question:
Which among the following is the feature of tuple in Swift?
A
A tuple type is a comma-separated list of types, enclosed in parentheses.
B
The values within a tuple can be of any type
C
Tuples can be decomposed into individual variables
D
All of the above
Answer: D
Explanation: A tuple type is a comma-separated list of types, enclosed in parentheses combining muliple values to single compound value.The values in a tuple can be of any type, and do not need to be of same type also tuples can be decomposed into individual variables
39 .
Topic:  Tuples
Question:
Which among the following cant be done with respect to tuples in swift?
A
return from functions
B
use of typealias keyword to name the tuple type
C
swap the tuple values
D
Sort the tuple values
Answer: D
Explanation: It is not possible to sort the tuple values as tuples hold different types of data. However we can swap the tuple values, can be returned froma function and tuple type can be named using type alias keyword.
40 .
Topic:  Tuples
Question:
How to swap the given tuples in swift? var a = 0 var b = 1
A
(a, b) = (b, a)
B
a.swap(b)
C
swap(a,b)
D
(a)=(b)
Answer: A
Explanation: (a)=(b) is used to swap the tuples in swift. After swapping b = 0 and a = 1
41 .
Topic:  Enums
Question:
Which among the following is true with respect to Enum in Swift? S1: Enum cases can contain one or more associated values. S2: Enums can be recursive S3: Enums can have custom init methods S4: Enums can be nested
A
S1,S2 and S3
B
S1,S3 and S4
C
S1,S2 and S4
D
S1,S2, S3 and S4
Answer: B
42 .
Topic:  Enums
Question:
Which keyword makes the enum store its payload with a layer of indirection in Swift?
A
indirect
B
payload
C
inline
D
raw
Answer: A
43 .
Topic:  Enums
Question:
Choose the correct statements
A
Enums cant have custom init methods
B
Enum can be created using rawValue
C
Enums without any specific type expose the rawValue property
D
Enums without payloads cant have raw values of any literal type:
Answer: B
44 .
Topic:  Enums
Question:
How to get enum value's corresponding raw value?
A
.rawValue
B
.raw
C
.value
D
.getRawValue
Answer: A
45 .
Topic:  Enums
Question:
What doe the hash value of specific enum return?
A
index of the enum starting from one
B
index of the enum starting from zero
C
last index
D
difference of first and last index of the enum
Answer: B
46 .
Topic:  Enums
Question:
Which among the following is true with respect to enum's raw values in Swift? S1: Integer raw values are assumed to start at 0 S2: Integer raw values increase monotonically S3: Raw-valued enum automatically conforms to RawRepresentable S4: String raw values cant be synthesized automatically
A
S1,S2 and S3
B
S2 only
C
S2,S3 and S4
D
S1, S3 and S4
Answer: A
47 .
Topic:  Structs
Question:
Which keyword enables a method of a struct to change the value of the struct itself in swift?
A
mut
B
mutating
C
mutable
D
Nsmut
Answer: B
48 .
Topic:  Structs
Question:
Which is false with respect to structs in swift?
A
Structures can adopt protocols
B
structures are passed through copying
C
Structs can be inherited
D
Structures can be compared using identity operator
Answer: C
49 .
Topic:  Structs
Question:
When can mutating methods be used in structs?
A
Inside variables
B
Inside constants
C
When let keyword is used
D
All of the above
Answer: B
50 .
Topic:  Structs
Question:
Which of the following throws error in swift with respect to structs?
A
class MyView: NSView { }
B
struct MyInt: Int { }
C
struct Vector: Hashable { ... }
D
None of the above
Answer: B