LoginSignup
22
14

More than 3 years have passed since last update.

RawRepresentableを知る

Posted at

はじめに

以前こんな記事を投稿しました

UITableviewにCaseiterableとCustomStringConvertibleを使ってみる

そこでRawRepresentableに出会ったのですが、RawRepresentableがなんなのかぼんやりとしか知らなかったので調べてみようと思いました。

RawRepresentableとは

定義

protocol RawRepresentable

For any enumeration with a string, integer, or floating-point raw type, the Swift compiler automatically adds RawRepresentable conformance.

RawRepresentableはEnumにString,Int,Floatを実装した場合デフォルトで追加されている。

var rawValue: Self.RawValue

Swiftのenumで自然に使っている、Hoge.hoge.rawValueのrawValueはRawRepresentableからきていて、RawRepresentableを実装していることによって値を持たせることができる

String,Int,Float以外でも、RawRepresentableを実装することによって値を持たせてあげることが可能になります。

値にアクセスする

rawValue

String,Int,Float以外でも実装すれば、値を持たせたり呼び出しに使うことが可能です

//RawRepresentableに対応していないためErrorになる
enum Color: UIColor {
    case red = UIColor.red
}

RawRepresentableを実装してあげることにより

enum Color {
    case red
}

extension Color: RawRepresentable {
    typealias RawValue = UIColor

    init?(rawValue: RawValue) {
        switch rawValue {
        case UIColor.red: self = .red
        default: return nil
        }
    }

    var rawValue: RawValue {
        switch self {
        case .red: return UIColor.red
        }
    }
}

Color.red.rawValueとして、UIColorをrawValueで使うことが可能になります

値を作成する

CustomStringConvertibleなどと組み合わせると

class ViewController: UITableViewController {

    enum IndexText: Int, CustomStringConvertible {
        case title1
        case title2
        case title3

        var description: String {
            switch self {
            case .title1: return "cat"
                        case .title2: return "dog"
                        case .title3: return "rabbit"
            }
        }
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell()
        //正しくない値が入った場合nilを返す
        cell.textLabel?.text = IndexText(rawValue: indexPath.row)?.description
        return cell
    }
}

RawRepresentableinit?(rawValue: Self.RawValue)を使うことにより、indexPath.rowで新しいインスタンスを作成し、とてもスッキリ書くことができます。

まとめ

・RawRepresentableはString,Int,Floatにデフォルトで実装されている
・Hoge.hoge.rawValueやinit?(rawValeu:)を使いインスタンス生成など様々な使い方ができる。

さらに詳しく

RawRepresentable

The RawRepresentable Protocol in Swift

22
14
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
22
14