swiftの関数の記述の仕方についてのメモ
func calc(line: Int, height: Int) -> Int {
return line * height
}
calc(line: 2, height: 12)
基本的に関数は上の様に記述する。
func
と記述することで関数であることを宣言する。
line
とheight
は引数で、それぞれ引数名と型を宣言する。
->
の右側に返り値の型を記述する。もしVoid
である場合には->
と返り値の型は省略出来る。
func say(_ sentence: String, to person: String) -> String {
return "\(sentence), \(person)"
}
say("Hello", to: "Jon")
よりswiftらしく記述するために、引数のラベルを置き換えたり、省略する事ができる。
第一引数は_
でラベルを省略出来る。
関数を呼び出す際にsay(sentence: "Hello", person: "Jon")
と記述することは、英語らしく読めないため、swiftでは好まれないとされています。
func create(name: String) -> (email: String, url: String) {
let email = "\(name)@email.com"
let url = "\(name).com"
return (email, url)
}
let newAcount = create("Mike")
print(newAcount.email)
print(newAcount.url)
タプルを用いた複数の値を返す関数も記述出来る。
func makeSquare() -> ((Int) -> Int) {
func square(number: Int) -> Int {
return number * number
}
return square
}
var squareMethod = makeSquare()
squareMethod(4)
関数は別の関数を値として返すことも出来る。
func recursiveCalcHeight(array: [String], lineNumber: CGFloat, buttonX: CGFloat) -> CGFloat {
let maxWidth = UIScreen.main.bounds.width
let buttonHeight: CGFloat = 14
guard let name = array.first else { return lineNumber * buttonHeight }
let button = UIButton()
button.setTitle(name, forState: .normal)
button.sizeToFit()
let buttonWidth = button.frame.width
let nextButtonX = buttonX + buttonWidth
let nextArray = Array(array.dropFirst())
if buttonWidth >= maxWidth {
return recursiveCalcHeight(array: nextArray, lineNumber: lineNumber, buttonX: buttonX)
}
if nextButtonX <= maxWidth {
return recursiveCalcHeight(array: nextArray, lineNumber: lineNumber, buttonX: nextButtonX)
}
return recursiveCalcHeight(array: nextArray, lineNumber: lineNumber + 1, buttonX: tagWidth + rightMargin)
}
上記のように末尾再帰関数を記述することができる。
上記は配列に含まれる名前のボタンを作成する際に、画面枠に収まらなかった際に行を一つ下げて、その全体の高さを最後に返します。