Search Your Question

Write a program for get only numeric from "a,b,1,2,c,4,d,3"

Ans :  

let string = "I have to buy 3 apples, 7 bananas, 10eggs"
let stringArray = string.components(separatedBy: CharacterSet.decimalDigits.inverted)
for item in stringArray {
    if let number = Int(item) {
        print("number: \(number)")


Output : 


Write a program to swap between two numbers without third variable

Ans : 

For Int : 

var x = 5
var y = 7

x = x + y
y = x - y
x = x - y


For Other Types :

var a = "a"
var b = "b"
(b, a) = (a, b)

What is better, Force unwrapping or optional binding?

Ans :

Force unwrapping :  It's the action of extracting the value contained inside an Optional. This operation is dangerous because you are telling the compiler: I am sure this Optional value does contain a real value, extract it!

let anOptionalInt: Int? = 1
let anInt: Int = anOptionalInt!

But here if, anOptionalInt has nil value, then fatal error will be generated. Unexpectedly found nil while unwrapping an Optional value.

Optional Binding: Using if let, we can store value in one variable if value is not nil. By this way, fatal error never be generated. This way will be used when we are not sure that variable has value or nil. This method is better because no chances of crashing app.

if let tempStockCode = stockCode {
    let message = text + tempStockCode

Implicitly unwrapped optionals : 

let anOptionalInt: Int! = 1
let anInt: Int = anOptionalInt

anOptionalInt is never be optional. But it can has value of nil.

How much memory will be occupied by integer computed property?

Ans :

No memory will be allocated for computed property. Computed property just compute value and return value. It is not stored any where.

Difference between encapsulation and abstraction.

Ans :

Encapsulation hides variables or some implementation that may be changed so often in a class to prevent outsiders access it directly. They must access it via getter and setter methods.
Abstraction is used to hiding something too but in a higher degree(class, interface). Clients use an abstract class(or interface) do not care about who or which it was, they just need to know what it can do.

Encapsulation: Wrapping code and data together into a single unit. Class is an example of encapsulation, because it wraps the method and property. 
Abstraction: Hiding internal details and showing functionality only. Abstraction focus on what the object does instead of how it does. It provides generalized view of classes.
int number = 5;
string aStringNumber = number.ToString(); 
Here, ToString() is abstraction. And how this mechanism number variable converted to string and initialize into aStringNumber is encapsulation.
We can achieve abstraction using protocol in iOS, achieve encapsulation using access control in class or struct.