Questions Seeker Questions Seeker - 1 year ago 67
Swift Question

One button that has multiple function - Swift

I am making an action button that implements different function each time the button is pressed. When I clicked once, the map changes to satellite and when i clicked it again, it changes to standard and when i clicked it again, it changes to hybrid and when i clicked it again, it goes back to satellite.

This is my code. Please let me know where did I do wrong.

@IBAction func changeLayout(_ sender: AnyObject) {
switch (sender.anyObject()) {
case 0:
mapView.mapType = MKMapType.satellite
case 1:
mapView.mapType = MKMapType.standard
mapView.mapType = MKMapType.hybrid


The error that I got says:

Expression pattern of type 'Int' cannot match values of type 'Any?' ViewController.swift

Answer Source

I assume the method is called by pressing an UIButton? If so, you can replace AnyObject with UIButton. Then you can use the UIButton's tag property to check the current state.

@IBAction func changeLayout(_ sender: UIButton) {
    sender.tag += 1
    if sender.tag > 2 { sender.tag = 0 }

    switch sender.tag { 
    case 1:
        mapView.mapType = .satellite
    case 2:
        mapView.mapType = .hybrid
        mapView.mapType = .standard

And to keep things 'Swiftly', you can remove the parentheses around the switch value as well as the enum's type. ;)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download