Search code examples
iosswiftsirikitnsorderedset

Swift 3 - How to declare an NSOrderedSet to use setVocabularyStrings?


I want to use this function's prototype for adding vocabulary to SiriKit. Apple's documentation shows the following sample code:

let workoutNames = self.sortedWorkoutNames()
let vocabulary = INVocabulary.shared()
vocabulary.setVocabularyStrings(workoutNames, of: .workoutActivityName)

According to the documentation, I need to use an NSOrderedSet type for self.sortedWorkoutNames().

How to declare it and set it with an array of Strings?

EDIT: About the context project, I'm using Intents with Siri. The goal here, is to use specific word like 'Benchpress' or 'Chicken' just to start my workout app with an INStartWorkoutIntent already implemented and working like a charm.


Solution

  • If you look at Apple's sample code for SiriKit, you can tell that their function sortedWorkoutNames() returns an NSOrderedSet. Look at the type of workoutNames in the Objective-C version:

    NSOrderedSet* workoutNames = [self sortedWorkoutNames];
    

    In Swift that would be

    let workoutNames: NSOrderedSet = self.sortedWorkoutNames()
    

    If you have an array that you want to pass to INVocabulary.setVocabularyStrings(_:of:), you'd need to convert it to an ordered set. As @larme said in his comment, NSOrderedSet has an initializer that takes an array as input.

    Your code might look like this:

    let myVocab = ["Benchpress", "Squats", "Deadlift"]
    let myVocabSet = NSOrderedSet(array: myVocab) //Convert myVocab to an NSOrderedSet
    
    let vocabulary = INVocabulary.shared()
    vocabulary.setVocabularyStrings(myVocabSet, of: .workoutActivityName)