Thursday, March 26, 2015

Swiftコード実行遅延





ネット上で探しました、簡単な例を見つけられませんでした。こちらで自分でやってみました。
「Click Pls」をタップすると3秒の後に「Result」ラベルで「clicked」を表示しましょう。そのためにビューコントローラーに次のコードを書きました。







import UIKit

class ViewController: UIViewController {

    @IBOutlet var resultLabel: UILabel!
    @IBAction func clicked(sender: UIButton) {
        func delay(delay:Double, closure:()->()) {
            dispatch_after(
                dispatch_time(
                    DISPATCH_TIME_NOW,
                    Int64(delay * Double(NSEC_PER_SEC))
                ),
                dispatch_get_main_queue(), closure)
        }
        delay(3) {
        self.resultLabel.text = "clicked"
        }
    }

}

結果的に「Click Pls」をタップすると3秒の後に「Result」ラベルで「clicked」が表示されます。

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)