pass a dictionary item as a parameter

Viewed 296

In my swift code below the goal is to pass a dictionary item as a parameter. It seems like this would work if it was a string but because I am trying to pass a item from a dictionary it does not work. I am passing from view did load to another function.

var girlsName = ["a": "Jessica Biel", "b": "Gwen Stefani","c":"Jessica Alba" ]

           override func viewDidLoad() {
    super.viewDidLoad()
    let index: Int = Int(arc4random_uniform(UInt32(girlsName.count)))
    let randomVal = Array(girlsName.values)[index]
    let randomVal2 = Array(girlsName.keys)[index]
   
   
    
}
@objc func submite( randomVal){

    print(randomVal)
  
    

    
}
3 Answers
  • Speak in an easy-to-understand way, you cannot pass parameters into an @objc function.

  • To pass parameters, you should use func instead of @objc func.

    func submit(dict: [String: String]) { print(dict) }

or if you want to pass a String as parameter:

func submit(aString: String) {
   print(aString)
}

You can pass a dictionary as a parameter like so:

func submit(dict: [String: String]){
    print(dict)
}

I am not sure exactly what you want to pass to the other function but you should use the function randomElement()

girlsName.randomElement() // a random key/value pair

girlsName.keys.randomElement() // a random key

girlsName.values.randomElement() // a random value

So if you want to pass a name (value) it could look like

submite(randomVal: girlsName.values.randomElement() ?? "")

if submite is declared as

func submite(randomVal: String) 
Related