I. Languageの
1. The Architecture of Swift
2. Functions
で不明点をまとめる
・Signatureとfullname
Signatureは型を示したもの
(Int, Int) -> Int
voidなら以下
() -> Void or () -> ()
関数のfull name
func echo(string s:String, times n:Int) -> String
を
echo(string:times:)
と書く
func say(_ s:String, times:Int){}
ならfull nameは以下
say(_:times:)
・Void型の省略
//以下は全部一緒 func say1(_ s:String) -> Void {print(s)} func say2(_ s:String) -> () {print(s)} func say3(_ s:String) {print(s)}
・anonymous
let function1 = {() -> () in print(test2) } let function2 = {(finish:Bool) -> () in print(finish) }
・クロージャーの省略
https://www.isoroot.jp/blog/3000/
//返り値を省略 let function3 = {() in print(test2)} let function4 = {(finish:Bool) in print(finish) } function3() function4(true) //引数を省略 let function5 = {print(test2)} function5() //型を省略。 //これやると何でも値通っちゃうんだけどな・・・・ let function6 = {(finish) in print(finish) } function6(true) function6("aaa") //かっこをとる let function7 = {finish in print(finish) } function7(false) function7("bbb") //$0を使う let function8 = {print($0) } function8(true) function8("ccc")
・completionを省略していく
UIView.animate(withDuration: 0.4, animations: {}, completion: {(finish:Bool) in print("aaa")}) //引数を使わない場合 UIView.animate(withDuration: 0.4, animations: {}, completion: {_ in print("aaa")}) //末尾の引数を外に出す UIView.animate(withDuration: 0.4, animations: {}) {_ in print("aaa")}
・mapでやってみた
let arr = [2, 4, 6, 8] let arr2 = arr.map({(i:Int) -> Int in return i*2}) print(arr) print(arr2) let arr3 = arr.map({(i:Int) -> Int in i*3}) print(arr3) let arr4 = arr.map({i -> Int in i*3}) print(arr4) let arr5 = arr.map({$0*3}) print(arr5)
・functionを返却
func function11() -> () -> Void { func f() { print("function11") } return f } function11()(); func function12() -> () -> Void { return { print("function12") } } function12()();
・参照渡し
func aaa(name s: inout String) { s = s + "!" } var masterka = "masterka" aaa(name: &masterka)
・@escaping
https://qiita.com/mishimay/items/1232dbfe8208e77ed10e
func funcPasser(f:@escaping () -> ()) -> () -> () { return f } funcPasser { print("funcPasser") }
・capture
//captureしないと数字があがる var x = 0 let f :()->() = { print(x) } f() //0 x=1 f() //1 //capture var xx = 0 let ff :()->() = { [xx] in print(xx) } ff() //0 xx=1 ff() //0
関連記事:
- iOS 15 Programming Fundamentals with SwiftのI-5とI-6を読んだので不明点をまとめる
- RxSwiftを使ってUISearchBarに入力した文字を取得する
- iOS 15 Programming Fundamentals with SwiftのI-3とI-4を読んだので不明点をまとめる