Skip to content

Instantly share code, notes, and snippets.

@KentarouKanno
Last active July 9, 2016 06:03
Show Gist options
  • Save KentarouKanno/30c38e168fa76032134a251e6feaab01 to your computer and use it in GitHub Desktop.
Save KentarouKanno/30c38e168fa76032134a251e6feaab01 to your computer and use it in GitHub Desktop.
Swift Tips

Swift Tips

let labelA = UILabel()
let labelB = UILabel()
let labelC = UILabel()

// ラベルの更新
func updateLabels() {
    
    (labelA: labelA.text, labelB: labelB.text, labelC: labelC.text) = {
        if /* condition1 */ true {
            return (labelA: "a", labelB: "b", labelD: "c")
        } else if /* condition2 */ true {
            return (labelA: "b", labelC: "B", labelB: "B")
        } else {
            return (labelA: "c", labelB: "C", labelC: "C")
        }
    }()
}

// ------------------------------------------------

// クロージャーの戻り値を決めてあげるとエラーが分かりやすい

var label = UILabel()
var button = UIButton()
var slider = UISlider()

enum Condition {
    case one, two, three
}


func updateValues() {
    
    let condition = Condition.one
    
    (label.text, button.selected, slider.value) = {
        () -> (text: String?, selected: Bool, value: Float) in
        switch condition {
        case .one:
            return (text: "1", selected: true, value: 0.1)
        case .two:
            return (text: 2, selected: false, value: 0.2)
            //error:
        //  cannot convert return expression of type 'Int' to return type 'String?'
        case .three:
            return (test: "3", selected: true, value: 0.3)
            //error:
            //  cannot convert return expression
            //  of type '(test: String, selected: Bool, value: Double)'
            //  to return type '(text: String?, selected: Bool, value: Float)' (aka '(text: Optional<String>, selected: Bool, value: Float)')
        }
    }()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment