Skip to content

Swiftの細かい文法のメモ

   

関数の引数は呼び出し側で省略したり、別名をつけたりすることができる。

func buyA(product: Int, price: Int, quantity: Int) {
    print(product, price, quantity)
}
buyA(product: 1200, price: 1500, quantity: 1)

func buyB(_ product: Int, _ price: Int, _ quantity: Int) {
    print(product, price, quantity)
}
buyB(123, 123, 123)

func buyC(a product: Int, b price: Int, c quantity: Int) {
    print(product, price, quantity)
}
buyC(a: 123, b: 123, c: 123)

関数が1行の場合は return を省略できる。

func messageA() -> String {
    return "Hello"
}

func messageB() -> String {
    "Hello"
}

return と同じ行に書いたコードは実行される。もちろんそれよりも下の行は実行されない。

func sayHello() {
    print("Hello")
    return print("XXX")
    print("YYY")
}

sayHello()
Hello
XXX

Swift で GOTO 的なことをする。

x: while true {
    y: while true {
        continue y
    }
}

Swift には repeat という繰返し方法がある。

var counter = 0
repeat {
    print("counter: \(counter)")
    counter = counter + 1
} while false
print("counter: \(counter)")
counter: 0
counter: 1

関連記事

  1. Swiftで数字が連番になった配列を作成する
  2. Swiftで引数を参照渡しをする
  3. iOSでMKMapViewの上に図形を描画する
  4. Swiftでプロジェクトの中に含まれるJSONファイルを読み込む
  5. SwiftでMKMapViewに図を追加する
  6. Swiftで配列からランダムに任意の個数抽出する
  7. TableViewのセルを長押しでContextMenuを表示する