Showing posts with label enum. Show all posts
Showing posts with label enum. Show all posts

Monday, 1 October 2018

Extensions

Extensions means add additional functionality to existing types.
Extensions add new functionality to existing class, struct, enum or protocols.
Extensions are similar to categories in Objective-C.

Extension syntax
Declare Extension with "extension" keyword

extension Type {
    ///Additional functionality add hear

}

An Extension can extends one or more protocols.

extension Type : Protocol{
    ///protocols method hear
}

Example

extension String{
    ///Trim string value
    func toTrim() -> String{
        return self.trimmingCharacters(in: .whitespacesAndNewlines)
    }
}

///Simply use like below
let strName = " use of string extension "
print(strName)
print(strName.toTrim())

Output : 

 use of string extension 
use of string extension

Another example

extension UIView {
    func defaultRadius() {
        self.layer.cornerRadius = self.frame.size.width / 2
    }
}

let parentView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: 50, height: 50))
parentView.backgroundColor = UIColor.red
parentView.defaultRadius()

Output: 

UIView Extension


Computed Properties

Extension can add computed instance property and computed type property to existing type.

Example

extension Int{
    var squareRoot : Int {
        return self * self
    }
}

let iValue = 5
print(iValue.squareRoot)

Output : 

25

Methods

Extensions add new instance method and type method to existence type.

Example

extension Int{
    func repeatValue(value : () -> Void) {
        for _ in 0..<self{
            value()
        }
    }
}

5.repeatValue {
    print("hello world")

}

Output :

hello world
hello world
hello world
hello world
hello world

For more about Extensions watch below video



Wednesday, 19 September 2018

Optional Types

Optional represents either wrapped value or nil.
Optionals are generic enum type that works as wrapper.

Basically wrapper allow variable have 2 states:

  1. User define type
  2. nil (that represent no value)
In swift nil value must be optional.
Optional can be created by appending either "?" or "!".

example :

var name : String? = nil
var lname : String! = nil

"?" must be explicitly unwrapped where as "!" automatically unwrapped.
Conditionally unwrapped use "?" optional binding where as force unwrapped use "!" operator. If you force unwrapped variable and value is nil then program will throw exception and crash so be careful.

example :

var lname : String! = nil
print(lname!)

Output :

fatal error: unexpectedly found nil while unwrapping an Optional value

Safe unwrapping :

Using if-let statement safe unwrap

example :

func safeUnwrap(withName name : String?){
    if let userName = name{
        print(userName)
    }else{
        print("name value is nil")
    }
}

safeUnwrap(withName: "Pratik")

Output :

Pratik

safeUnwrap(withName: nil)


Output :

name value is nil

Using guard-let statement safe unwrap

example :

func safeUnwrap(withName name : String?){
    guard let userName = name else{
        print("user name not found")
        return
    }
    print(userName)
}

safeUnwrap(withName: "Pratik")

Output :

Pratik

safeUnwrap(withName: nil)


Output :

user name not found

Using Coalescing operator safe unwrap

example :

var name : String? = nil
print(name ?? "name value is nil")


Output :

name value is nil

var name : String? = nil
name = "Pratik"
print(name ?? "name value is nil")


Output :

Pratik

You can also use Optional chaining in order to call method,property or subscript.

example : 

struct Family{
    func printName() {
        print("Hello friends")
    }
}

var objFamily : Family?
objFamily?.printName()

Output :

no print 

var objFamily : Family? = Family()
objFamily?.printName()

Output :

Hello friends



unwrapped using optional type in swift
Optional types unwrapped

Sunday, 9 September 2018

Tuples

Why Tuples ?
Swift 4 has introduced tuples to help us to return multiple values from a function instead of only one value.
Tuples is multiple values grouped into a single compound value. The values can be of any type, it need not necessarily to be of same type.
Tuples type is comma-seperated list types, enclosed in parentheses.
Tuples are created by grouping any amount of values.

Please check below examples for different uses of tuples :
---------------------------------------------------------------------------------
Displaying tuple value using variable name

1) Same Data type

let multipleValue : (value1 : String,value2 : String) = ("iOS","Android")

print(multipleValue.value1)
print(multipleValue.value2)

Output
iOS
Android
---------------------------------------------------------------------------------
Different Data type

1) Displaying tuple value using index (without variable name)

let multipleValue = ("iOS""Android"5)

print(multipleValue.0
print(multipleValue.1)
print(multipleValue.2)

Output :
iOS
Android
5

2) Displaying tuple value using variable names

let multipleValue = (name: "iOS",name1: "Android",value1: 5)

print(multipleValue.name)
print(multipleValue.name1)
print(multipleValue.value1)

Output :
iOS
Android
5
---------------------------------------------------------------------------------
Displaying tuples as optionals

var multipleValue : (name: String,name1: String?,value1: Int)
multipleValue = ("iOS",nil,5)

print(multipleValue.name)
print(multipleValue.name1)
print(multipleValue.value1)

Output
iOS
nil
5

---------------------------------------------------------------------------------
Tuples usage in function return type

1) Displaying tuple value using index (without variable name)

func test() -> (String,Int) {
    return ("iOS",11)
}

print(test().0)
print(test().1)

Output
iOS
11

2) Displaying tuple value with variable name


func test() -> (name : String,version : Int) {
    return ("iOS",11)
}
print(test().name)
print(test().version)

Output
iOS
11
---------------------------------------------------------------------------------

For more info, click on below link :-

https://www.youtube.com/watch?v=MwOv844k9-4&t=222s




Thank you.


Monday, 3 September 2018

Enum

Enum is data type for consisting name value like String, Int etc.
For good programer practice code is readable and reusable.
Enum is best for comparing in conditional statement and switch case.

For example if we match string type value like

func getDevice(forDeviceType deviceType : String){
    if deviceType == "iOS"{
        print("iOS")
    }else{
        print("Other device")
    }
}

Now how to use enum string type for above function 
enum enumDeviceType : String {
    case iOS
    case Android
}

func getDevice(forDeviceType deviceType : String){
    if deviceType == enumDeviceType.iOS.rawValue{
        print("iOS device")
    }else{
        print("Other device")
    }

}

another example of enums
enum myEnumList{
    case list1
    case list2
    
    var noOfItems : Int{
        switch self {
        case .list1:
            return 50
        case .list2:
            return 100
        }
    }
}

func listEnumTest(type : myEnumList)
{
    switch type {
    case .list1:
        print("hello list 1 total item is \(type.noOfItems)")
        break
    case .list2:
        print("hello list 2 total item is \(type.noOfItems)")
        break
    }
}

listEnumTest(type: .list1)

you can also watch video 




If you have any trouble in use of enum then pls comment 

Thank you


Wednesday, 29 August 2018

Generics in iOS Swift

The main use of Generic is avoid code duplication.
Generic placeholder is defined within angle brackets <>.

For example there are two array with different type.

let arrayOfInt = [5,10,15,20]
let arrayOfString = ["Karan","Ankur","Bunty"]

For print this array of value you can create two function like

func printInt(fromArrayOfInt arrayOfInt:[Int]){
    arrayOfInt.map({print($0)})

}

func printString(fromArrayOfString arrayOfString:[String]){
    arrayOfString.map({print($0)})
}

And use

printInt(fromArrayOfInt: arrayOfInt)
printString(fromArrayOfString: arrayOfString)

Output:

5
10
15
20
Karan
Ankur
Bunty

Now using Generic no need to create two function. We can print all type of array using single function like 


func printArray<T>(fromArray arrayOfValue: [T]){
    arrayOfValue.map({print($0)})
}

and calling is same

printArray(fromArray: arrayOfInt)
printArray(fromArray: arrayOfString)

In order to use Generic with struct, class or enum, you can define the Generic placeholder after the name. 

Github link : Generics

You can also watch video :