1

I have class as shown below:

struct Cur: Decodable {
    let id: String
    let name: String
    let symbol: String
    let switchVal:Bool
}

This class populates an array and the array is being displayed in UITableView. How to detect which switch button (switchVal) is toggled, therefore how to get "id" of the related element.

I am detecting when UISwitchButton is toggled inside a prototype cell like this:

@IBAction func switchBtn(_ sender: UISwitch) {
     if sender.isOn {

     }
}
4
  • Not related to your question but don't use implicitly unwrapped optionals in your properties Commented Oct 24, 2017 at 22:59
  • 1
    btw defining your switchVal a constant false makes no sense Commented Oct 24, 2017 at 23:00
  • 1
    And isOn is a non optional Bool. Using == true is redundant. To check if not isOn just use if !sender.isOn Commented Oct 24, 2017 at 23:12
  • 1
    Fixed that too, thank you! Commented Oct 24, 2017 at 23:21

1 Answer 1

2

You can use index(where:) method to find the index of your array element as follow:

struct Cur: Decodable {
    let id: String
    let name: String
    let symbol: String
    let switchVal: Bool
}

let cur1 = Cur(id: "a", name: "john", symbol: "j", switchVal: false)
let cur2 = Cur(id: "b", name: "steve", symbol: "s", switchVal: true)
let cur3 = Cur(id: "c", name: "Carl", symbol: "c", switchVal: false)

let list = [cur1, cur2, cur3]

if let index = list.index(where: {$0.switchVal}) {
    print(list[index]) // Cur(id: "b", name: "steve", symbol: "s", switchVal: true)\n"
    print(list[index].id)  // "b\n"
}
Sign up to request clarification or add additional context in comments.

1 Comment

Hello, I am sure your code will work flawlessly and thank you for that. However, I am getting error "fatal error: unexpectedly found nil while unwrapping an Optional value". I am sure this has to do with my force-unwraps. Have to figure out those optionals. Thank you!

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.