1

I am trying to randomize the arrayList and then pull the URL to an IBAction that would then open the page.

override func viewDidLoad() {
    let ArrayList = [
        ["A", "A2", "http://a.com"],
        ["B", "B2", "http://b.com"],
        ["C", "C2", "http://c.com"],
    ]

    let pickArrayList = ArrayList[Int(arc4random_uniform(UInt32(ArrayList.count)))]
    label1.text = pickArrayList[0]
    label2.text = pickArrayList[1]
}

Below is the IBAction but I receive an error saying that pickArrayList[2] is an unresolved Identifier.

@IBAction func didTapButton(sender: AnyObject) {
        UIApplication.shared.open(URL(pickArrayList[2])!)  
    }

Thanks in advance, Swift Noobie

1 Answer 1

1

The error occurs because pickArrayList is declared as local variable in the scope of viewDidLoad.

Declare pickArrayList as a property on the top level of the class

var pickArrayList : [String]!

override func viewDidLoad() {
    super.viewDidLoad()
    let arrayList = [
        ["A", "A2", "http://a.com"],
        ["B", "B2", "http://b.com"],
        ["C", "C2", "http://c.com"],
    ]

    pickArrayList = arrayList[Int(arc4random_uniform(UInt32(arrayList.count)))]
    label1.text = pickArrayList[0]
    label2.text = pickArrayList[1]
}

Please conform to the naming convention that variable names start with lowercase letter.

Sign up to request clarification or add additional context in comments.

4 Comments

Man this is so close. I get a "fatal error" because it says there is a bad execution within the @IBAction. "UIApplication.shared.open(URL(string: pickArrayList[2])!)" If I remove the "string:" then I get an error that "Argument Labels (_:) do not match any available overloads."
URL(string: .. is mandatory. Make sure that string in pickArrayList[2] is a valid URL format or use optional binding.
Okay, so I have tried a bunch of different URLs and none have worked thus far. When I change the string value to "google.com" as opposed to pickArrayList[2], it has no problem. Any thoughts?
Once again, the string must be convertible to URL. Check the url in a browser or a playground. URL(string: returns nil if the URL format is not valid. But this is beyond the issue of the question.

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.