0

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;
              }

1
  • var readPermSet = NSSet() => var readPermSet = NSMutabmeSet() and then, readPermSet.add(val), but why do you keep using NSArray and NSSet? Can't you use Swift Set and Array instead? Commented Apr 9, 2021 at 8:42

2 Answers 2

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)
Sign up to request clarification or add additional context in comments.

Comments

1

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;
 }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.