Swift实现NSOptions(多选枚举)

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
    }
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容