Upgrade to Pro — share decks privately, control downloads, hide ads and more …

復習OptionSet

 復習OptionSet

Tomohiro Nishimura

December 26, 2016
Tweet

More Decks by Tomohiro Nishimura

Other Decks in Technology

Transcript

  1. &OVNFSBUJPO let permissions: [Permission] = [.read, .create] func read() {

    guard permissions.contains(.read) else { forbidden() return } showReadViewController() }
  2. &OVNFSBUJPO w ϦιʔεͷύʔϛογϣϯͱϢʔβʔͷݖݶ w ͜ͷϦιʔεʹରͯ͜͠ͷϢʔβʔ͕Մೳͳૢ࡞͸ ͳΜͳͷ͔ w ͞Βʹάϧʔϓຖʹݖݶ͕͋ͬͨΓ͢Δͱʜ let resourcePermissions:

    [Permission] = [.read] let userPermissions: [Permission] = [.read, .create, .edit, .delete] resourcePermissions.filter { permission in return userPermissions.contains(permission) }
  3. #JUXJTFPQFSBUJPO // _ _ _ _ delete edit create read

    // 0 0 0 0 1 1 1 1 struct Permission { static let read: UInt8 = 0b00000001 static let create: UInt8 = 0b00000010 static let edit: UInt8 = 0b00000100 static let delete: UInt8 = 0b00001000 } 6*OUʹ໊લ͚ͭΔͱྑͦ͞͏ʜ
  4. #JUXJTFPQFSBUJPO let permissions: UInt8 = Permission.read | Permission.create func read()

    { guard (permissions & Permission.read) != 0 else { forbidden() return } showReadViewController() }
  5. #JUXJTFPQFSBUJPO w ͜ͷϦιʔεʹରͯ͜͠ͷϢʔβʔ͕Մೳͳૢ࡞͸ ͳΜͳͷ͔ let resource: UInt8 = Permission.read let

    user: UInt8 = Permission.read | Permission.create | Permission.edit | Permission.delete let currentPermission = resource & user
  6. 0QUJPO4FU struct Permission: OptionSet { let rawValue: UInt8 static let

    read = Permission(rawValue: 1 << 0) static let create = Permission(rawValue: 1 << 1) static let edit = Permission(rawValue: 1 << 2) static let delete = Permission(rawValue: 1 << 3) }
  7. 0QUJPO4FU let permissions: Permission = [.read, .create] func read() {

    guard permissions.contains(.read) else { forbidden() return } showReadViewController() }
  8. 4FU"MHFCSB func contains(Self) func insert(Self) func update(with: Self) func remove(Self)

    func union(Self) func intersection(Self) func symmetricDifference(Self) func formUnion(Self) func formIntersection(Self) func formSymmetricDifference(Self)
  9. 4FU"MHFCSB let p: Permission = [.read, .create, .edit] let o:

    Permission = [.edit, .delete] p //=> 0111 o //=> 1100 p.union(o) //=> 1111 p.intersection(o) //=> 0100 p.symmetricDifference(o) //=> 1011
  10. 0QUJPO4FU w ͜ͷϦιʔεʹରͯ͜͠ͷϢʔβʔ͕Մೳͳૢ࡞͸ ͳΜͳͷ͔ let resource: Permission = [.read] let

    user: Permission = [.read, .create, .edit, .delete] let current: Permission = resource.intersection(user)
  11. ΍Γ͍ͨ switch userPermission { case Permission.read: print("Can Read") fallthrough case

    Permission.create: print("Can Create") fallthrough case Permission.edit: print("Can edit") fallthrough case Permission.delete: print("Can delete") }
  12. ༇շͳ஥ؒͨͪ w 6*$POUSPM4UBUF w OPSNBM w EJTBCMFE w FUDʜ button.setTitle("དྷ೥΋",

    for: .normal) button.setTitle("ؔϞό", for: [.highlighted, .selected]) button.setTitle("ΑΖ͘͠", for: .disabled)