Swift UIDeviceOrientation(enum)やUIInterfaceOrientation(enum)のrawValueを文字列表示

UIDeviceOrientationとUIInterfaceOrientationはenum

extensionでtoString()実装

extension UIDeviceOrientation {
    func toString() -> String {
        var result = ""
        switch self.rawValue {
        case 0:
            result = "unknown"
        case 1:
            result = "portrait"
        case 2:
            result = "portraitUpsideDown"
        case 3:
            result = "landscapeLeft"
        case 4:
            result = "landscapeRight"
        case 5:
            result = "faceUp"
        case 6:
            result = "faceDown "
        default:
            break
        }
        return result
    }
}

Javaエンジニアの発想、仕事はJava使用率高ですが。

extentionでコンピューテッドプロパティ description実装

extension UIDeviceOrientation {
    public var description: String {
        var result = ""
        switch self.rawValue {
        case 0:
            result = "unknown"
        case 1:
            result = "portrait"
        case 2:
            result = "portraitUpsideDown"
        case 3:
            result = "landscapeLeft"
        case 4:
            result = "landscapeRight"
        case 5:
            result = "faceUp"
        case 6:
            result = "faceDown "
        default:
            break
        }
        return result
    }
}

ちょっとSwiftぽく。

extentionでCustomStringConvertibleプロトコル適用

extension UIDeviceOrientation: CustomStringConvertible {
    public var description: String {
        var result = ""
        switch self.rawValue {
        case 0:
            result = "unknown"
        case 1:
            result = "portrait"
        case 2:
            result = "portraitUpsideDown"
        case 3:
            result = "landscapeLeft"
        case 4:
            result = "landscapeRight"
        case 5:
            result = "faceUp"
        case 6:
            result = "faceDown "
        default:
            break
        }
        return result
    }
}

正解!?

memo

リフレクション使用して出来れば良いが、現時点では見つからなかった。

Swift

Posted by shi-n