Skip to content

Instantly share code, notes, and snippets.

@sahara-ooga
Created October 30, 2020 09:22
Show Gist options
  • Save sahara-ooga/db83e301ddd58ff829092a149ee34f51 to your computer and use it in GitHub Desktop.
Save sahara-ooga/db83e301ddd58ff829092a149ee34f51 to your computer and use it in GitHub Desktop.
Swiftの`is`演算子

Swiftのis演算子は、サブクラスでもマッチする。

例:

あるUIViewControllerのサブビューのうち、UIViewのみを削除したいとする。

for view in self.view.subviews {
    if view is UIView {
        view.removeFromSuperview()
    }
}

とすると、もしviewがUIViewのサブクラスであるUIButtonクラスやUIImageViewのインスタンスだったとしても、view is UIViewtrueになってしまう。 もし、サブクラスのインスタンスを対象から外したい場合は、

for view in self.view.subviews {
    if type(of: view) == UIView.self {
        view.removeFromSuperview()
    }
}

のように、type(of:) == T.self としてtype(of:)を使う必要がある。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment