Monday, March 23, 2015

Swift: How to Update Variable Outside the Scope of Function



Apple Swift brings some new ways of coding practices which might be challenging for developers who already are used to Java, C# and other object oriented languages. One of such areas for me was seemingly simple one - how to update variables outside of functions (which are often used as methods) due to restrictions on function scope and variable optionals in Swift. Here, i give simple example in Xcode playground where two variables (score1 and score2) are given functions to return values and then summed up for another valuable (totalScore).

import UIKit

    var score1:Int? = 6
func getScore1 () -> (Int?) {

    if score1 != nil {
        score1
    } else {
        score1 = 0
    }
    return (score1)
}

var score2:Int? = nil
func getScore2 () -> (Int?) {
    
    if score1 != nil {
        score1
    } else {
        score1 = 0
    }
    return (score1)
}

var totalScore = getScore1()! + getScore2()!

println(totalScore)

2 comments:

  1. If I understand you thought correctly, I think it is somewhat more beautiful and more "object-oriented" to use setters and getters in this case.
    Here's an example of Farenheit <--> Celsius convertor class (stolen from somewhere) using setters and getters for its property:

    import Darwin

    class Temperature {
    var celsius: Float = 0.0
    var fahrenheit: Float {
    get {
    return (celsius * 1.8) + 32.0
    }
    set {
    celsius = (newValue - 32) / 1.8
    }
    }
    }


    let temperature = Temperature()
    temperature.celsius = 30;
    temperature.fahrenheit; // prints the the equivalent in Fahrenheit

    ReplyDelete