• Skip to main content
  • Skip to primary sidebar

Ravi Shankar

Tweaking Apps

  • Swift
  • Tech Tips

Apple

How to request a refund for apps in App Store

November 2, 2021 By Ravi Shankar

Apple provides users with the option to get a refund for app. Here are the steps for submitting a refund request.

  • Launch  reportaproblem.apple.com and login using your Apple ID.
  • In “What can we help you with” drop down select the option as “Request a refund”.

  • In “Tell us more” drop down select the reason why you need a refund.
  • Then select the app for which you need a refund and click on the Submit button.
  • You will receive a email once your request has been processed. Use the “Check status of claim” to find out whether you have request has been approved.
  • Filed Under: App Refund, Apple, Tips

    Tab Bar Controller with WebView

    April 9, 2020 By Ravi Shankar

    In this article, we will see step by step instruction on working of Tab Bar Controller, UIWebView and Activity Indicator by loading couple of web pages using UIWebView in two different Tabs.

    Tab Bar Controller

    Tab Bar Controller is used for organising list of View Controllers by having seperate tabs for each View Controller. Check out the Apple Documentation for more information.

    UIWebView

    When you want to allow users to browse website then you can use UIWebView to load those pages. These WebViews needs to be placed inside a container such as UIViewController. Check out Apple Documentation for more information on UIWebView.

    Project Setup

    Create a new project by selecting Single View Application as project template. You can also choose Tabbed Application but in this demo we will see how to embed a ViewController inside a Tab Bar Controller.

    Enter the project details and select the language as Swift.

    Embed View Controller inside Tab Bar Controller

    Navigate to Main.storyboard in Project Navigator and select View Controller. Now to embed this View Controller inside a Tab bar Controller, click Editor -> Embed In -> Tab Bar Controller

    The Interface builder should now display View Controller and Tab Bar Controller as shown below.

    Add Second View Controller

    Now let us see how to add another tab by setting relationship between second View Controller and Tab Bar Controller. Drag and drop UIViewController from Object library to Interface builder.

    Control + Drag from Tab Bar Controller to UIViewController and select view controllers under Relationship Segue. This should add second tab bar item pointing the second View Controller.

    Add UIWebView and Activity Indicator View

    We are not using Auto Layout or Size Classes for this demo, so disable these features using the option available under File Inspector.

    Drag and drop UIWebView from object libary to both the View Controllers. Make sure it is aligned centrally to View Controller and covers the entire View Controller area. Similarly add Activity Indicator View from object libary to top of UIWebView and align to the Centre both vertically and horizontally.

    Edit Tab Bar Items

    The Tab Bar Controller display two tab bar items which are linked to each View Controller. Add required images for each Tab bar items to the Images.xcassets (Download the images from GitHub project).
    To provide a name and image for Tab Bar items, select the item in the corresponding View Controller and enter the details in Attributes Inspector. For the first View Controller, the name and image are set as shown below.

    repeat the same for the second View Controller as well.

    Link class with UIViewController

    The project comes with a default ViewController.swift file which is mapped with the first View Controller. Let us give a proper name to this controller. Unfortnately Xcode Refactor option still does not work for Swift (Xcode version 6.4). Manually rename the file to WorldViewController.swift and also make the corresponding name change in Class.

    class WorldController: UIViewController {
    
    

    Add a second view controller class by right clicking the project, select New File option.

    In the choose template screen, select Cocoa Touch Class and provide name as SportsViewController making it a subclass of UIViewController.

    Create IBOutelts for UIWebView and Activity Indicator View

    Using Assistant Editor, navigate to Main.storyboard in the second window. In the Identity Inspector, set the class name for both ViewControllers to WorldViewController and SportsViewController.

    Drag and drop UIWebView from WorldViewController (Interface builder) to WorldViewController.swift to create IBOutlet. Do the same for Activity Indicator View as well.

    @IBOutlet weak var webView: UIWebView!
    
    @IBOutlet weak var activityIndicator: UIActivityIndicatorView!

    Repeat the same exercise for SportsViewController and create corresponding IBOutlets.

    Code Implementation

    Navigate to WorldViewController.swift file and add the following code snippet in ViewDidLoad function.

    let url = NSURL(string: "http://edition.cnn.com/world")
    let urlRequest = NSURLRequest(URL: url!)
    webView.loadRequest(urlRequest)
    
    activityIndicator.startAnimating()
    activityIndicator.hidesWhenStopped = true

    The first three lines of the code create a NSURLRequest and the object is passed to UIWebView loadRequest function. The last two lines starts the Activity Indicator View and sets the property to hide the indicator when it is stopped animating.

    We need to tell the Activity Indicator when the page has finished loading. This can be done by implementing UIWebViewDelegate’s webViewDidFinishLoad function.

    Add the following piece of code to make the View Controller as a delegate for webView.

    class WorldController: UIViewController, UIWebViewDelegate {

    and in the viewDidLoad function add webView.delegate = self. This would ensure that the View Contorller can handle any WebView delegate related calls.

    Now implement the webViewDidFinishLoad function and stop the animation of Activity Indicator View when the webview has finished loading the page.

    //MARK:- WebView Delegate method
    
        func webViewDidFinishLoad(webView: UIWebView) {
            activityIndicator.stopAnimating()
        }
    

    Repeat the above code implementation for SportsViewController excepy by chaning the URL string.

    class SportsViewController: UIViewController, UIWebViewDelegate {
        @IBOutlet var webView: UIWebView!
        @IBOutlet var activityIndicator: UIActivityIndicatorView!
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            let url = NSURL(string: "http://edition.cnn.com/sport")
            let urlRequest = NSURLRequest(URL: url!)
            webView.loadRequest(urlRequest)
    
            activityIndicator.startAnimating()
            activityIndicator.hidesWhenStopped = true
    
            webView.delegate = self
        }
    
        override func didReceiveMemoryWarning() {
            super.didReceiveMemoryWarning()
            // Dispose of any resources that can be recreated.
        }
    
        //MARK:- UIWebView Delegate methods
        func webViewDidFinishLoad(webView: UIWebView) {
            activityIndicator.stopAnimating()
        }
    
    }
    
    

    When you finally build and run the project, you should see the follwing on iOS simulator.

    Download the source code from here

    Filed Under: Apple, ios, Programming, Xcode

    Get your current address in Swift (Swift 5)

    November 7, 2019 By Ravi Shankar 22 Comments

    In this Swift tutorial, we will see the steps required for using CoreLocation framework and retrieve the latitude and longitude of the location. Then use the CLGeocoder to reverse geocode the latitude and longitude details. This is a very basic tutorial that retrieves the location details on tap of a button and displays the information on the screen.

    Updated :- The source has now been to updated to show the address details in TextFields.

    Click File -> New and select Project sub menu list.

    201407251656.jpg

    In the Choose a template screen, select Single View Application and click Next button.

    201407251657.jpg

    Enter the product name as WhereAmI and select the language as Swift then click Next. Select a folder and create the new project and that folder.

    201407251658.jpg

    Navigate to ViewController.swift file and add a new function with name as findMyLocation after viewDidLoad function.

    @IBAction func findMyLocation(sender: AnyObject) {
    
    }

    Navigate to Main.storyboard file, drag and drop Button from the Object Library on to the View Controller. Using the attributes inspector, change the name of the button to “Where Am I?”. If you need then change the background and text colour for the button. Then centre align the button both vertically and horizontally. Use the Resolve Auto Layout Option and pick Reset to Suggested Constraints.

    201407251707.jpg

    Navigate to Connections Inspector and connect the button to the findMyLocation action under Received Actions (Touch Up Inside event).

    201407251711.jpg

    Click the Project under Project Navigator and navigate to Build Phases. Click the + sign under Link Binary With Libraries and pick CoreLocation.framework from the list.

    Add CoreLocation framework to Swift project201407251718.jpg

    CoreLocation in Swift

    Now navigate back to ViewController.swift file, add import CoreLocation after UIKit. Then we need to assign the current class as the delegate for CLLocationManagerDelegate. This is required because we will be using couple of delegate methods from CLLocationManager.

    class ViewController: UIViewController, CLLocationManagerDelegate {

    Define a constant for CLLocationManager after the class declaration.

    let locationManager = CLLocationManager()

    Navigate to IBAction function findMyLocation and add the following code

    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.requestWhenInUseAuthorization()
    locationManager.startUpdatingLocation()

    The above lines sets the class as delegate for locationManager, specifies the location accuracy and starts receiving location updates from CoreLocation. In order to get the location updates we need to implement the delegate functions of CLLocationManager, didUpdateLocations and didFailWithError

    func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
    }
    
    func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
    }
    

    didUpdateLocations function is triggered when new location updates are available. Similarly didFailWithError is called when there is a problem receiving the location updates. Let us first start implementing the simpler one i.e didFailWithError function. When there is an error, we are going to log the message to the console.

    func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
    	println("Error while updating location " + error.localizedDescription)
    }

    Then update didUpdateLocations function with the following code, also add a new function for printing the location details.

    func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
    CLGeocoder().reverseGeocodeLocation(manager.location, completionHandler: {(placemarks, error)->Void in
    		if error {
    			println("Reverse geocoder failed with error" + error.localizedDescription)
    			return
    		}
    
    		if placemarks.count > 0 {
    			let pm = placemarks[0] as CLPlacemark
    			self.displayLocationInfo(pm)
    		} else {
    			println("Problem with the data received from geocoder")
    		}
    	})
    }
    
    func displayLocationInfo(placemark: CLPlacemark) {
    	if placemark != nil {
    		//stop updating location to save battery life
    		locationManager.stopUpdatingLocation()
    		println(placemark.locality ? placemark.locality : "")
    		println(placemark.postalCode ? placemark.postalCode : "")
    		println(placemark.administrativeArea ? placemark.administrativeArea : "")
    		println(placemark.country ? placemark.country : "")
    	}
    }
    

    in the didUpdateLocations function, we pass the location co-ordinates to

     CLGeocoder().reverseGeocodeLocation

    . Then check for error and process the location array (placemarks). Then for displaying the location details, we pass the placemark detail to displayLocationInfo function.

    Add key to Info.plist for request permission to User’s location

    In order to use the user’s location you need to request permission from the user by adding the keys “NSLocationWhenInUseUsageDescription” or “NSLocationAlwaysUsageDescription” to your Info.plist file, with the value blank or optionally a message included in the prompt to the user. One of those two key is required in iOS 8 to ask for your location.

    Testing Location in Simulator

    It is not possible to test current location with simulator. So we need to define a custom location or use the location already defined for debug purpose. When an app tries to access the location services on a simulator it displays the following popup.

    Current Location Simulator Xcode 6

    Here is a workaround to test the app using Xcode 11. Run the app on the a Simulator and tap “Find My Location” button. Nothing will happen as the app has not been given permission to use Location Services on Simulator.

    201407251956.jpg

    Click Debug menu then Location and select Apple from the sub menu list. Still nothing happens with the app and no messages are written to the console.

    201407251957.jpg

    Now click Hardware menu and select Home from menu list.

    201407251959.jpg

    Tap the Settings icon on Simulator -> Privacy -> Location -> Tap , select Always to allow the app to access the location.

    201407252003.jpg201407252005.jpg

    Now you should see Apple address details in the Console Output.

    201407252008.jpg

    You can also try out other location using the Simulate Location option.

    Simulate location in Xcode 6 simulator

    Hopefully the testing should be lot easier after issue with “Allow to use Current Location” is fixed.

    Source from GitHub

    Filed Under: Apple, Develop, ios, Programming, Xcode Tagged With: Apple, CoreLocation, Swift, Xcode

    Add line numbers in Word 2013, Word 2010 and Word 2007

    September 27, 2015 By Ravi Shankar Leave a Comment

    Microsoft Word users can add line numbers to a word document using the options available as part of Page Layout menu. In this tutorial we will see the steps for adding line number in Word 2013 and Word 2011 for Mac.

    How to add line numbers in Word 2007, Word 2010, Word 2013 and Word 2011 for Mac

    Word 2007 Word 2010 and Word 2013

    Word 2010 allows users to add line numbers to a word document. This can be done using the Page Layout menu option. For example if you have the following text in your document and you want insert line numbers for each line then you use this feature.

    image

    To add line numbers for above paragraph, from Home menu click the Page Layout menu option and then navigate to Page Setup section.

    Page Layout Menu in Word 2013 and Word 2010

    In the Page Layout section, click the drop down arrow next to Line Numbers menu option. This would display the following menu options.

    Line numbers in Word 2013 and Word 2010

    Now select Continuous from the list available menus and this would insert the line numbers in the Word document as shown below

    Document with line numbers in Word 2010 and Word 2013

    The other line numbers options includes

    • Restart Each Page – To restart line numbers after each page.
    • Restart Each Section – To restart line numbers after each section.
    • Suppress for Current Paragraph – to remove line numbers for the selected paragraph.

    Word 2011 for Mac

    Step 1: Open the document for which you want to add line number.

    Word 2011 for Mac Layout Menu

    Step 2: Click Layout menu and navigate to Text Layout section.

    Step 3: Now click the Line Numbers option under Text Layout. This should display the following drop down list.

    Word 2011 for Mac Continuous numbers

    Step 4: Select Continuous from the Line numbers drop down list to add line numbers. You can also customise Line numbers by use other options in the list.

    Show line numbers in document

    If you are looking for advanced line number options then click More Line Numbering.

    More line numbers option

    Display of line number in status bar

    If you just want to find out the current line number while editing a document then you can use line number option available as part of status bar for this purpose.

    Word 2007, Word 2010 and Word 2013

    Microsoft Word 2007 and Word 2010 provides option to display the line numbers in a word document. This would be a useful feature when you want to restrict your content based on the number of lines written in the document. If the status bar does not show the line numbers, then right click on the Status bar and select Line number.

    Display line number in status bar in Word 2013, Word 2010 and Word 2007

    After selecting Line Number option in the Customize Status Bar context menu, the status bar would display the line number as shown below.

    Show line numbers in Word status bar

    Word 2011 for Mac

    Word 2011 for Mac does not support the display of line number in status bar. This option is available in Window’s version of Microsoft Word but not in Mac OS X.

    Also See: How to auto populate random sentences in Word 2010

    Filed Under: Apple, Mac, MS Office, Office 2010, Office 2013, Word 2007, Word 2010, Word 2013 Tagged With: Apple, Line numbers, Mac, Page Layout, Show Line numbers, Status Bar, Word 2011 for Mac

    Reset and Erase content on iPad

    August 25, 2015 By Ravi Shankar Leave a Comment

    In this tutorial we will be covering about the Reset and Erase content feature available on iPad 2. Press the Home button on your iPad and tap the settings icon available on the Home screen.

    In the Settings page, navigate to Reset option. This would display the following list of options.

    If you are planning to sell your iPad then don’t forget to remove all your personal photos, documents and other files from your iPad. You can do this by tapping on the Erase All Content and Settings option.

    And If you are facing problems with your iPad then probably you can the Reset All Settings option to see if that resolves the problem.

    The Reset feature also provides users with the option for resetting only the Network Settings or Keyboard Dictionary or Home Screen Layout or Location Warnings. Depending upon the need you can choose these options. For example if you have problems in reconnecting to an already established network then you can reset the network settings and try again connecting with the network.

     

    Filed Under: Apple, iPad Tagged With: Erase, Home Screen, iPad 2, Keyboard, Layout, network, Remove, reset, Settings

    Prevent installing or uninstalling apps on iPad or iPhone

    June 25, 2015 By Ravi Shankar 1 Comment

    Prevent

    In this tutorial we will be see the steps required to prevent any users from installing or uninstalling any apps on iPad or iPhone. This is a useful tip if you are sharing your iPad with other people especially kids and do not want them accidentally uninstall and install any Apps.

    To prevent users from removing or installing apps, press the menu button on your iPad and tap the Settings icon.

    image

    In the General Settings, tap the Restriction option and enable restrictions by setting a passcode. In the Restrictions screen, navigate to Installing Apps and Deleting Apps Option.

    image

    By tapping them and changing the value to Off would prevent users from removing or installing any apps on iPhone or iPad.

    Filed Under: Apple, iPad Tagged With: apps, Install, iPad 2, prevent, Remove, Uninstall

    Closures, Extensions and Generics in Swift

    May 22, 2015 By Ravi Shankar Leave a Comment

    Closures

    Closures are self contained lines of code that can be passed around the application and similar to blocks in Objective-C. A typical closure syntax in Swift looks as shown below

    Closure Syntax

    [code language=”swift”]{ (parameters) -> return type in
    statements
    }[/code]

    Example closure in Swift

    [code language=”swift”]{ (name:String, message:String -> (String) in
    message + ” ” + name + ” !!!”
    }
    greetings(“Ravi”,”Welcome”)
    [/code]

     

    In the above code example, a closure has been assigned to a variable. The purpose of this closure is to concatenate the string parameters and return the appended message as return parameter.

    Type Inference

    The example closure can modified to ignore to the parameter types and closure supports type inference.

    [code language=”swift”]var greetings = { (name, message) -> (String) in
    return message + ” ” + name + ” !!!”
    }

    greetings(“Ravi”,”Welcome”)[/code]

    Implicit return

    In single expression closure, you can omit the return keyword.

    [code language=”swift”]var numbers = [23,45,67,89,89,78]
    numbers.sort { (number1, number2) -> Bool in
    return number1 < number2
    }

    // numbers.sort { number1, number2 in return number1 < number2 }
    numbers.sort { number1, number2 in number1 < number2 } // Shorthand argument syntax
    numbers.sort { $0 < swift }[/code]

    Shorthand Argument Syntax

    Swift supports shorthand argument names for inline closures. In the above example used for implicit returns, the two parameters can be removed and represented in shorthand arguments as shown below.

    [code language=”swift”]numbers.sort { $0 < swift }
    [/code]

    Trailing Closure

    In a function with closure as the last parameter, the closure can be treated as trailing closures i.e closures outside the function parenthesis call. This is quite helpful in reducing the long closure expression. For example, the sorted function has closure as the last parameter and with trailing closure this becomes as shown below.

    [code language=”swift”]var numbers = [23,45,67,89,89,78]
    var sortedNumbers = sorted(numbers, {$0 > swift}) // Without trailing closure
    // var sortedNumbers = sorted(numbers) {$0 > swift} // represented as trailing closure

    sortedNumbers[/code]

    Extensions

    Swift extensions are similar to category in Objective-C which adds new functionally to existing class, enumeration or Struct. Extension does not require the source code of original class or enumeration type or struct to extend their functionality.

    Listed below is an example which extends String class. A new function fromDouble has been added to String class which takes a double value and returns String.

    [code language=”swift”] extension String {
    static func fromDouble(doubleValue: Double) -> String {
    var temp = String(format: “%.2f”, doubleValue)
    return temp as String
    }
    }
    String.fromDouble(24.50)[/code]

    Generics

    Generics are code that produces the same result irrespective of the data type. Listed below is a function that accepts an array of type string and reverses the array items.

    [code language=”swift”]let strTemp = [“Deepak”,”John”,”Steve”,”Ravi”,”Ganesh”]

    // reverse array with String
    func reverseString(items: Array) -> Array {
    var temp = Array()
    return items.reverse()
    }
    reverseString(strTemp)[/code]

    Now the below function accepts array of number and reverses the items

    [code language=”swift”] let numbers = [23,45,56,78,98]
    // reverse array with numbers
    func reverseNumber(items: Array) -> Array {
    return items.reverse()
    }
    reverseNumber(numbers)[/code]

    Generics solves the problem of having different set of code for different data types by implemting the functionality for a generic type.

    [code language=”swift”]let strTemp = [“Deepak”,”John”,”Steve”,”Ravi”,”Ganesh”]
    let numbers = [23,45,56,78,98]

    func reverseItems(items:[T])-> [T] {
    return items.reverse()
    }
    reverseItems(strTemp)
    reverseItems(numbers)[/code]

    You can also implement a Generic class with this function as shown below.

    [code language=”swift”]let strTemp = [“Deepak”,”John”,”Steve”,”Ravi”,”Ganesh”]

    class ReverseDemo {
    func reverseItems(items:[P])-> [P] {
    return items.reverse()
    }
    }
    let reverseDemo = ReverseDemo()
    reverseDemo.reverseItems(strTemp)
    [/code]

    Swift Operations with Generics

    Let us say you want to create a generic function that returns the square value of the given number. The immediate solution that comes to your mind is

    [code language=”swift”]func squareOfNumber(number:M -> M{
    return number * number
    }
    [/code]

    This is not as straight forward as we think, you would notice an error – “Binary operator ‘*’ cannot be applied to two M operands”. The generic data type does not recogonize the operator ‘*’. We can fix this by creating a new protocol that tells about this operator ‘*’ and Generic type should conform to this protocol as shown below.

    [code language=”swift”]protocol Multipliable {
    func *(lhs:Self, rhs: Self) -> Self
    }

    func squareOfNumber(number:M -> M{
    return number * number
    }
    [/code]

    Then add an extension to Int, Float and other required types and make them conform to Multipliable protocol.

    [code language=”swift”]extension Int: Multipliable {}
    extension Float: Multipliable {}

    squareOfNumber(20)[/code]

    Download source code from gitHub (Generic)

    Filed Under: Apple, Develop, ios, Programming Tagged With: Closures, Extensions

    Tuples, Enums and Protocols in Swift

    May 14, 2015 By Ravi Shankar Leave a Comment

    Tuples in Swift allows user to assign group of values to a variable, constant and even return parameter of a function. In the below example, a employee constant is assigned Int and String values. And to access these parameters, we need to use .0 and .1

    [code language=”swift”]let employee = (103, “Deepak”)
    employee.0
    employee.1[/code]

    Now let us say you want to assign proper name for these parameters so that you could access these values using those names instead of 0 and 1.

    [code language=”swift”]let employee = (id:103, name:“Deepak”)
    employee.id
    employee.name[/code]

    Here id and name are parameter names provided for employee id and employee name. You can also declare the data types for the tuple values like Int and String

    [code language=”swift”]let employee:(id:Int, name:String = (102, “Deepak”)
    employee.id
    employee.name[/code]

    Tuples and switch cases are powerful combination, look at an example below where Tuple has been used with switch cases. The _ is used for matching any values.

    [code language=”swift”]let employee:(id:Int, name:String) = (102, “Deepak”)
    switch (employee) {
    case (103…105,_):
    println(“developer”)
    case (106…108,_):
    println(“tester”)
    case (_,“Deepak”):
    println(“CEO”)
    default:
    println(“Contractor”)
    }[/code]

    Enums

    Enum in Swift allows users to group related values to a single data type. Swift enum has lot of new features compared to its predecessor Objective-C. Let us see this with an example enum type for all Months in a year.

    [code language=”swift”]enum Months {
    case January, February, March, April, May, June, July, August, September, October, November, December
    }

    enum Month {
    case January, February, March, April, May, June, July, August, September, October, November, December
    }[/code]

    Now you can define a variable or a constant of type month as shown below.

    [code language=”swift”]let currentMonth = Month.May[/code]

    And variable or constant is declared with the data type then you can use the short form.

    [code language=”swift”]let currentMonth:Month = .May[/code]

    Enum with Raw Value

    Enum in Swift can be assigned a RawValue when declaring and the value can be of any data type. Let us day you want to specify the String value of each Month

    [code language=”swift”]enum Month: String {
    case January = “January”, February = “February”, March = “March”, April = “April”, May = “May”, June = “June”, July = “July”, August = “August”, September = “September”, October = “October”, November = “November”, December = “December”
    }[/code]

    The RawValue can be printed by accessing .rawValue on the enum variable or constant.

    [code language=”swift”]let currentMonth:Month = .May
    currentMonth.rawValue[/code]

    Enum with Associated Value

    Same like RawValue, enum can also have associated value and of data type.

    [code language=”swift”]enum Month {
    case January(String), February(String), March(String), April(String), May(String), June(String), July(String), August(String), September(String), October(String), November(String), December(String)
    }

    let currentMonth:Month = .May(“Summer Vacation”)

    switch currentMonth {
    case .May(let message):
    println(message)
    default:
    println(“No Values”)
    }[/code]

    In the above example, Month enum values are declared with an associated value of data type String. And while assign the enum value the associated value is also provided to the currentMonth constant. Using the switch the associated value is retrieved.

    Enum can have member function

    Enum in Swift can also have member function. In the below example code, we have declared the Month enum with rawValue of type Int. Now add a member function to calculate the number of months left from the currently assigned value.

    [code language=”swift”]enum Month: Int {
    case January = 1, February, March, April, May, June, July, August, September, October, November, December func monthsLeftForYearEnd() -&gt; Int {
    return Month.December.rawValue – self.rawValue
    }
    }

    let month: Month = .May
    month.monthsLeftForYearEnd()[/code]

    Constant month is assigned a enum value of .May and you can find out the number of months left for the year end by accessing the monthsLeftForYearEnd.

    Enum can have Initialiser

    Swift’s enum can have initialiser too where you can set the default enum value or do some initial processing. If you add init function as shown below, the default enum value will be set to July.

    [code language=”swift”]enum Month: Int {
    case January = 1, February, March, April, May, June, July, August, September, October, November, December
    init() {
    self = .July
    }

    func monthsLeftForYearEnd() -&gt; Int {
    return Month.December.rawValue – self.rawValue
    }
    }

    let month = Month()
    month.monthsLeftForYearEnd()[/code]

    Protocols

    Protocol in Swift defines the contract for a class or struct. This is similar to the interface in other languages like java. Protocol only defines the member function or variables and the actual implementation should be done in the conforming class or struct. Protocol can be be useful in the following ways

    • To add common behaviour across related or unrelated classes.
    • Supports in the implementation of delegation pattern

    Let us see a typical example of protocol in Swift where we defining a Protocol called LivingThings with one method eat.

    [code language=”swift”]protocol LivingThings {
    func eat() -&gt; String
    }[/code]

    Any class or struct conforming to this Protocol should add implementation to eat method. In the below code example, we have got two classes Animal and Human which conform to LivingThings. implementation for the eat method has been added to both the classes.

    [code language=”swift”]class Animal: LivingThings {
    func eat() -&gt; String {
    return “Animal Food"
    }
    }

    class Human: LivingThings {
    func eat() -&gt; String {
    return "Human Food"
    }
    }

    let john = Human()
    john.eat()

    let cat = Animal()
    cat.eat()[/code]

    If a class conforming to a Protocol does not implement the required methods then you will find error message “error: type ‘Human’ does not conform to protocol ‘LivingThings’”

    Protocol with Optional Methods

    In Swift, Protocol with optional method can be defined by specifying the optional before the method definition and adding @objc keyword before protocol. Listed below is an example with Speakable protocol that has an optional method speak

    [code language=”swift”]
    protocol LivingThings {
    func eat() -&gt; String
    }

    @objc protocol Speakable {
    optional func speak() -&gt; String
    }

    class Human: LivingThings, Speakable {
    func eat() -&gt; String {
    return "Human Food"
    }

    func speak() -&gt; String {
    return "Human can Speak"
    }
    }

    let john = Human()
    john.eat()
    john.speak()[/code]

    Protocol and Delegation Pattern

    A delegate pattern is used when you want a class to act on behalf of another class or for a callback mechanism. In the below code example we have defined a protocol (ImportDataDelegate) with two methods startImport and finishedImport. The DataImport class conforms to this Protocol and adds implementation to these methods. The DemoImport class acts on behalf of DataImport class by declaring a variable delegate of type ImportDataDelegate.

    [code language=”swift”]protocol ImportDataDelegate {
    func startImport()
    func finishedImport()
    }

    class DataImport: ImportDataDelegate {
    func startImport() {
    println("Import started")
    }

    func finishedImport() {
    println("Import finished")
    }
    }

    class DemoImport {
    var delegate: ImportDataDelegate?

    func startProcess() {
    delegate?.startImport()
    println("Doing some work …")
    delegate?.finishedImport()
    }
    }[/code]

    This is how you pass the DataImport class to delegate variable of the DemoImport.

    [code language=”swift”]let demoImport = DemoImport()
    demoImport.delegate = DataImport()
    demoImport.startProcess()[/code]

    Filed Under: Apple, Develop, ios, Programming Tagged With: Apple, delegate pattern, Optional Methods, Protocol

    1. Pages:
    2. 1
    3. 2
    4. 3
    5. 4
    6. 5
    7. 6
    8. 7
    9. »
    Next Page »

    Primary Sidebar

    TwitterLinkedin

    Recent Posts

    • How to block keywords in Jio broadband
    • How to disable opening an app automatically at login in Mac
    • How to set preferred Wifi network on Mac
    • Attribute Unavailable: Estimated section warning before iOS 11.0
    • How to recover Firefox password from Time Machine backup

    Pages

    • About
    • Privacy Policy
    • Terms and Conditions

    Copyright 2022 © rshankar.com

    Terms and Conditions - Privacy Policy