0%

位运算

位运算了解一下,哈哈哈哈哈哈…

Person.swift

import Foundation

extension Bool {
    init(_ integer: Int){
        self.init(integer != 0)
    }
}

struct Person {
    
    let TallMask = (0b00000001 << 0b00000000)
    let RichMask = (0b00000001 << 0b00000001)
    let HandsomeMask = (0b00000001 << 0b00000010)
    
    var _tallRichHandsome = 0b00000000
    
    mutating func setTall(_ tall: Bool) {
        if tall {
            _tallRichHandsome = (_tallRichHandsome | TallMask)
        } else {
            _tallRichHandsome = (_tallRichHandsome & ~TallMask)
        }
    }
    
    func isTall() -> Bool {
        return Bool(_tallRichHandsome & TallMask)
    }
    
    mutating func setRich(_ rich: Bool) {
        if rich {
            _tallRichHandsome = (_tallRichHandsome | RichMask)
        } else {
            _tallRichHandsome = (_tallRichHandsome & ~RichMask)
        }
    }
    
    func isRich() -> Bool {
        return Bool(_tallRichHandsome & RichMask)
    }
    
    mutating func setHandsome(_ handsome: Bool) {
        if handsome {
            _tallRichHandsome = (_tallRichHandsome | HandsomeMask)
        } else {
            _tallRichHandsome = (_tallRichHandsome & ~HandsomeMask)
        }
    }
    
    func isHandsome() -> Bool {
        return Bool(_tallRichHandsome & HandsomeMask)
    }
}

main.swift

import Foundation


var person = Person()

print(person.isTall())
print(person.isRich())
print(person.isHandsome())
print("================")
print(person._tallRichHandsome)
print("===================")
person.setTall(true)
person.setRich(true)
person.setHandsome(true)
print(person.isTall())
print(person.isRich())
print(person.isHandsome())

print("===================")
//print(person.TallMask)
//print(person.RichMask)
//print(person.HandsomeMask)
person.setTall(false)
print(person.isTall())
print(person.isRich())
print(person.isHandsome())

print("==================")
//print(0b00000000)
//print(0b00000001)
//print(0b00000010)

print("==================")

print(person._tallRichHandsome)

–EOF–