微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在Swift中声明特定类类型的枚举?

我正在尝试创建一个类,并使用该类作为我的新枚举的类型,如下所示.

class Abc{
    var age  = 25
    var name = "Abhi"
}

enum TestEnum : Abc {
    case firstCase
    case secondCase
}

我在操场上遇到以下错误.

error: raw type 'Abc' is not expressible by any literal

所以我尝试遵循这样的RawRepresentable协议.

extension TestEnum : RawRepresentable{
    typealias RawValue = Abc

    init?(rawValue:RawValue ) {
        switch rawValue {
        case Abc.age :
            self = .firstCase

        case Abc.name :
            self = .secondCase
        }
    }

    var rawValue : RawValue {
        switch self{

        case .firstCase :
            return Abc.age

        case .secondCase :
            return Abc.name
        }
    }
}

我在此之后遇到以下错误

error: raw type 'Abc' is not expressible by any literal
error: instance member 'age' cannot be used on type 'Abc'
error: instance member 'name' cannot be used on type 'Abc'

声明某个类类型的枚举的正确方法是什么,而不是对此有明确的想法.有人帮吗?

解决方法

来自Docs

In particular,the raw-value type must conform to the Equatable
protocol and one of the following protocols:
ExpressibleByIntegerLiteral for integer literals,
ExpressibleByFloatLiteral for floating-point literals,
ExpressibleByStringLiteral for string literals that contain any number
of characters,and ExpressibleByUnicodeScalarLiteral or
ExpressibleByExtendedGraphemeClusterLiteral for string literals that
contain only a single character.

因此,让您的类Abc符合Equatable和上述协议之一.这是一个例子

public class Abc : Equatable,ExpressibleByStringLiteral{
    var age  = 25
    var name = "Abhi"
    public static func == (lhs: Abc,rhs: Abc) -> Bool {
        return (lhs.age == rhs.age && lhs.name == rhs.name)
    }
    public required init(stringLiteral value: String) {
        let components = value.components(separatedBy: ",")
        if components.count == 2 {
            self.name = components[0]
            if let age = Int(components[1]) {
                self.age = age
            }
        }
    }
    public required convenience init(unicodeScalarLiteral value: String) {
        self.init(stringLiteral: value)
    }
    public required convenience init(extendedGraphemeClusterLiteral value: String) {
        self.init(stringLiteral: value)
    }
}

enum TestEnum : Abc {
    case firstCase = "Jack,29"
    case secondCase = "Jill,26"
}

现在你可以初始化你的枚举了

let exEnum = TestEnum.firstCase
print(exEnum.rawValue.name) // prints Jack

有关详细讨论和示例,您可以参考
https://swiftwithsadiq.wordpress.com/2017/08/21/custom-types-as-raw-value-for-enum-in-swift/

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐