iOS Development Knowledge Brush Up 10-10: Part 2


1. What is KVC or Key-Value Coding

KVC is a mechanism to access an object’s property indirectly using string. It is only possible if a class inherits NSObject class.

class X: NSObject{
    let name:String?
    
    init(name:String) {
        self.name = name
    }
}

let x = X(name: "Jack")
x.name
x.value(forKey: "name")

If you remove the NSObject super class in the code, then the value property will not work and will show compile error.

2. What is Key-Path expressions?

Using #keyPath() expression you can access properties dynamically.

class Person: NSObject {
    @objc var name: String
    @objc var friends: [Person] = []
    @objc var bestFriend: Person? = nil
    
    init(name: String) {
        self.name = name
    }
}
 
let gabrielle = Person(name: "Gabrielle")
let jim = Person(name: "Jim")
let yuanyuan = Person(name: "Yuanyuan")
gabrielle.friends = [jim, yuanyuan]
gabrielle.bestFriend = yuanyuan
 
#keyPath(Person.name)
// "name"
gabrielle.value(forKey: #keyPath(Person.name))
// "Gabrielle"
#keyPath(Person.bestFriend.name)
// "bestFriend.name"
gabrielle.value(forKeyPath: #keyPath(Person.bestFriend.name))
// "Yuanyuan"
#keyPath(Person.friends.name)
// "friends.name"
gabrielle.value(forKeyPath: #keyPath(Person.friends.name))
// ["Yuanyuan", "Jim"]

3. What is implicitly unwrap optionals?

If it is certain that an optional always have a value after the value is first set, in that case checking optional every time, it is better to declare that optional as implicitly unwrap optional.

//will not compile
var name:String? = "Jack"
let newName:String = name  //need to unwrap
newName
//implicitly unwrap optional work no need unwrap logic
var name:String! = "Jack"
let newName:String = name
newName

4. When we may need to use Assertions or Preconditions

Assertions and preconditions are one kind of checking that happens at runtime. These can be used to satisfy certain condition before executing further code.

Assertions only checked in debug build.

let age = 17
assert(age >= 18, "Under Age")

Preconditions are checked in both debug and release build.

let age = 17
precondition(age >= 18, "Under Age")

OR, we can check the condition ourself and call assertion failure or precondition failure

if age < 18 {
    assertionFailure("Under Age")
}

5. What and how many types are Range opertors

There are 3 type of range operators:
i) Closed Range
It defines a range (a…b) that runs from a to b and includes b. Value of a must not be greater than b.

for i in 1...3{
    print(i) // 1, 2, 3
}

ii) Half-Open Range
It defines a range (a..<b) that runs from a to b but not includes b.

for i in 1..<3{
    print(i) // 1, 2, 3
}

iii) One-Sided Range
It defines a one side direction as far as possible. For example, in the following code the one side range will visit all the elements of the array.

let num = [1, 2, 3, 4, 5]
for x in num[0...]{
    print(x)
}

6. How to use multiline String literals

Use “”” and “”” to start and end of the multiline String literals.

let address = """
Kampung "Lapan",
Melaka, Malaysia
"""

7. Are String in Swift reference or value type?

Swift String type is value type. Whenever a new string is created or passed as a function parameter or assigned to a variable and constant in each case a new copy of the existing string is created.

8. How to use String Indices

Swift String value doesn’t have integer indices. Because each character can take different memory space. String type associated with String.Index, which represents each position of the character in the string.

To access different position’s character use index method and offsetBy property.

let name = "Mahmud Ahsan"
let pos2 = name.index(name.startIndex, offsetBy: 1)
name[pos2] //a

9. What is Substring type and why we need to use that?

When we retrieve part of a string that is a result of Substring type. It is introduced in Swift 4.0 for performance optimization. Substring can re-use part of memory where original String is stored. Unless the Substring or String is modified it will not copying memory thus improve performance. The rule is, use substring for short-term storage and for long-term storage use String. Both String and Substring conforms the StringProtocol.

let x = "Life is Good"
let xPart = x.prefix(4) //xPart is Substring
let xFull = String(xPart) //long-term storage

10. Can String and Substring mutually comparable and can operate

Yes, both String and Substring conform to the StringProtocol protocol. So when you use String operation you can pass either String type and Substring type values.

Challenges:

1. What is wrong with this code?

var (x, y) = (1, 2)
if x = y{
	//do something
}   

2. Is it correct?

let x = "My name is " + " Khan"

3. What is the value of the following code?

let x = -9 % 4

a) 1
b) 0
c) -1
d) -2

4. Which one is wrong statements?

var age = 13
age++
++age
age = age + 1
age += 1

5. What is the value of personType constant?

var age = 13
let personType = age < 18 ? "Not Adult" : age > 50 ? "Senior" : "Normal"

6. What is the output of the following code?

let num = [1, 2, 3, 4, 5]
for x in num[2...]{
    print(x)
}

7. What is wrong with the following code?

let name = "Mahmud Ahsan"
for x:Character in name{
    print(x)
}

8. What is the output of the following code?

let name = "Mahmud Ahsan"
let pos:String.Index = name.index(name.endIndex, offsetBy: -2)
name[posEnd]

a) n
b) a
c) will not compile
d) s

9. Guess the value of the newName and finalName constants?

var name = "Mahmud Ahsan"
name.insert("X", at: name.index(after: name.startIndex))
let newName = name

name.remove(at: name.index(name.startIndex, offsetBy: 1))
let finalName = name

newName
finalName

10. What is the output of the following code?

let x = "Good"
let y:Substring = "Good"

if x == y{
    print("equal")
}

a) nothing
b) equal
c) will not compile

Answers:

1. It will not compile. Because assignment operation in Swift doesn’t return a value. Though it works in both C and Objective-C.
2. Yes, + is used for String Concatenation in Swift
3. c) -1 is the right answer
4. age++ and ++age are wrong statements. These unary operators are not available in Swift.
5. The value is: Not Adult
6. 3, 4, 5
7. There is nothing wrong. String characters are represents by Character type.
8. b) a is the right answer
9. newName = “MXahmud Ahsan”, finalName = “Mahmud Ahsan”
10. b) equal is the right answer

mahmud ahsan

Computer programmer and hobbyist photographer from Bangladesh, lives in Malaysia. My [Github | Business | Twitter | Linkedin | Instagram | Flickr | 500px]

You may also like

LEAVE A COMMENT