0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

[Swift] 即時関数について

0
Last updated at Posted at 2021-04-08

即時関数

現在ハンズオン形式でアプリ開発をしているのだが
理解不能なコードと遭遇した。
調べてみると即時関数を使用したコード。

原稿のコードがこれ

private var chatInputAccesoryView: ChatInputAccessaroyView = {
    let view = ChatInputAccessaroyView()
    view.frame = .init(x: 0, y: 0, width: view.frame.width, height: 100)
    return view
}

あるクラスをコンポーネントをクラスとして定義。
別のビューコントローラーでインスタンスを生成する。

わかりやすく書くとこうなる。

               )
private var chatInputAccesoryVie<--ただの変数--> : ChatInputAccessaroyView<--クラス型の宣言--> = {
    let view = ChatInputAccessaroyView() //インスタンスを生成 

    <--生成したオブジェクトのプロパティを変更->
    view.frame = .init(x: 0, y: 0, width: view.frame.width, height: 100)
    return view//戻り値
}

訳のわからないコードで騙されたが
private var chatInputAccesoryView: ChatInputAccessaroyViewは
private var hensuu:String
と意味合い的には変わらないただの変数の宣言である。

戻り値としてviewが変数chatInputAccesoryViewに格納される。
chatInputAccesoryViewの実態はプロパティが変更されたChatInputAccessaroyViewクラスの実体ということになる。

わかりやすくテストコードを書いてみた。

import UIKit

private var test: testclass{
    let x = testclass()
    x.a = 3
    return x
};()

class testclass{
    var a = 1
    func print(){
        Swift.print(a)
    }
}
print(test.a)

結果は3が出力される。

ここでの即時関数のメリットは
コードを簡潔にかけること。
オブジェクトのプロパティを自由に定義できる

これで合ってるのかは自分も初学者なのでわからないが...
動きさえ分かっていれば使う時に使えるようになればいいか!

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?