加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 04:53:29 所属栏目:百科 来源:网络整理
导读:我正在尝试创建一个类,并使用该类作为我的新枚举的类型,如下所示. 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
我正在尝试创建一个类,并使用该类作为我的新枚举的类型,如下所示.

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/

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读