skip to Main Content

How can i append my HKObjectTypes into a NSSet.
It always returns empty. Any better way???

     func getPermsFromOptions(_ options: NSArray) -> NSSet {
            var readPermSet = NSSet()
            var optionKey: String
            var val: HKObjectType
                
           for i in options{
            optionKey = i as! String
            val = HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier(rawValue: optionKey))!

             readPermSet.adding(val)    
             print("set", readPermSet)           //always empty

                      }
                  return readPermSet;
              }

2

Answers


  1. readPermSet.adding(val)
    

    Adding isn’t a mutating method, it returns a new set that has the other value added

    Try it with:

    var readPermSet: Set<HKObjectType> = []
    

    and

    readPermSet.insert(val)
    
    Login or Signup to reply.
  2. You cannot add to an NSSet. You can add to an NSMutableSet:

    var readPermSet = NSMutableSet()
    ...
    readPermSet.add(val)
    

    adding is a method from Swift, that returns a new set with all the same elements, plus the new element. You are ignoring its return value here.

    Since you are in Swift, why not use Set<HKObjectType> and [String]?

    func getPermsFromOptions(_ options: [String]) -> Set<HKObjectType> {
        var readPermSet = Set<HKObjectType>()
        for optionKey in options {
            let val = HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier(rawValue: optionKey))!
             readPermSet.insert(val)    
             print("set", readPermSet)
         }
         return readPermSet;
     }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search