美文网首页
Swift实现NSOptions(多选枚举)

Swift实现NSOptions(多选枚举)

作者: 林夕copy | 来源:发表于2019-12-11 18:24 被阅读0次

OC中的NSOptions通过位运算可以实现多选枚举,swift版本如下:

struct StringJoinType: OptionSet {
    let rawValue: Int
    static let joinName    = StringJoinType(rawValue: 1 << 0)
    static let joinAge     = StringJoinType(rawValue: 1 << 1)
    static let joinAddress = StringJoinType(rawValue: 1 << 2)
    static let joinJob     = StringJoinType(rawValue: 1 << 3)
    static let joinBase: StringJoinType = [.joinName, .joinAge]
    static let joinAll: StringJoinType = [.joinBase, .joinAddress, .joinJob]
}

创建struct实现OptionSet协议,并通过位运算定义枚举值。枚举值的使用例子:
通过枚举值创建一个字符串

func optionsTest() -> String {
        let type: StringJoinType = .joinBase
        var result = ""
        if (type.contains(.joinName)) {
            result.append("Albert")
        }
        
        if (type.contains(.joinAge)) {
            result.append("12")
        }
        
        if (type.contains(.joinAddress)) {
            result.append("github")
        }
        
        if (type.contains(.joinJob)) {
            result.append("iOS")
        }
        return result //输出结果:Albert12
    }

相关文章

网友评论

      本文标题:Swift实现NSOptions(多选枚举)

      本文链接:https://www.haomeiwen.com/subject/cvragctx.html