Implement follow unfollow button with mutating function Swift

To modify the properties of a value type, you have to use the mutating keyword in the instance method. This keyword gives your method can then have the ability to mutate the values of the properties and write it back to the original structure when the method implementation ends.

Add follow button as shown in the UIViewController below inside the UITableView Prototype cell.

Add Protocol Togglable.swift:

protocol Togglable {
    mutating func toggle()
}

Add FollowStatus.swift class with the below code that implements Togglable Protocol:

enum FollowStatus: Togglable {
    case follow, unfollow
    
    mutating func toggle() {
        switch self {
            case .follow:
                self = .unfollow
            case .unfollow:
                self = .follow
        }
    }
}

Inside the UITableViewCell class, add the follow Action method:

class TableViewCellClass: UITableViewCell {
    @IBOutlet weak var followBtn: UIButton!
    var followStatus: FollowStatus = .follow

    @IBAction func followBtnTapped(_ sender: Any) {        
        followStatus.toggle()
        if followStatus == .unfollow{
            followBtn?.setTitle("unfollow",for: .normal)
        }
        else {
            followBtn?.setTitle("follow",for: .normal)
        }
    }
}

Run the App and test clicking the button to see the status of the button changing between follow/unfollow.

Using Xcode version 10.1.

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.