1
2

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 3 years have passed since last update.

[Swift5] required 修飾子とは

Last updated at Posted at 2021-11-26

用途

  • サブクラスに、イニシャライザのオーバーライドを強制するとき
  • プロトコルのイニシャライザをオーバーライドするとき

また、

required 修飾子は、イニシャライザ init() でのみ使用可能。

インスタンスメソッドでは使用不可。

サブクラスに、イニシャライザのオーバーライドを強制する時

例:

class Animal {
    let name: String

    //
    // A(サブクラスにイニシャライザのオーバーライドを強制するときは、required 修飾子を付ける)
    //    
    required init() {
        self.name = "unknown"
    }
}

class Cat: Animal {
    //
    // A をオーバーライド(override 修飾子ではなく、required 修飾子を使うことに注意)
    //
    required init() {
        super.init()
    }
}

ポイント

  • サブクラスにイニシャライザのオーバライドを強制する場合、スーパクラスとサブクラスの両方にrequiredをつける。

プロトコルのイニシャライザをオーバライドする時

例:

protocol SomeProtocol {
    //
    // A
    //
    init()
}

class Animal: SomeProtocol {
    //
    // A をオーバーライド
    //
    required init() {
    }
}

ポイント

  • protocolのイニシャライザはrequiredをつけない
  • protocolのイニシャライザをオーバーライドする時につける

参考

https://qiita.com/cotrpepe/items/3931c0c20ef43f4a18ac

1
2
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
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?