LoginSignup
2
4

More than 5 years have passed since last update.

[Swift]enumにextensionを生やす

Last updated at Posted at 2018-01-27

rawVauleのあるenumに対してextensionを生やす場合はRawRepresentableに対してextensionを行えばOK

enumにメソッドを生やす

enum Animal: String {
  case fox
}

extension RawRepresentable {
  func printRawValue() {
    print(rawValue)
  }
}

Animal.fox.printRawValue() //fox

Stringのenumにメソッドを生やす

RawValueに型情報が入っているのでそれを見る

enum Animal: String {
  case fox
}

extension RawRepresentable where Self.RawValue == String {
  func printRawValue() {
    print(rawValue)
  }
}

Animal.fox.printRawValue()
2
4
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
2
4