Search code examples
iosiphoneswiftgeneric-programming

How to write a common generic function for different classes?


func setPostcommentData(postmodel:model1,index: IndexPath) {
     btnReply.tag = index.section
     lblName.text = postmodel.getFullName()
     btnReply.setTitle("Reply", for: UIControlState.normal)
     btnCount.setTitle("0", for: UIControlState.normal)
     TxtViewComment.text = postmodel.description
     lblTime.text = ChatDates.commentTimeData(postmodel.createdDate).dateString
}

Usage:

cellComment.setPostcommentData(postmodel: model1,index:indexPath) 
cellComment.setPostcommentData(postmodel: model2,index:indexPath) 
cellComment.setPostcommentData(postmodel: model3,index:indexPath) 

How to write generic function so that it accepts different models and sets data?


Solution

  • If I got the idea right, here is a solution

    protocol PostComment {
        var value1: String {get}
        var value2: String {get}
        var value3: String {get}
    }
    
    class PostCommentParent: PostComment {
        var value1: String {
            return self.myValue1
        }
    
        var value2: String {
            return self.myValue2
        }
    
        var value3: String {
            return self.myValue3
        }
    
        var myValue1 = "1"
        var myValue2 = "2"
        var myValue3 = "3"
    }
    
    class PostCommentChild: PostCommentParent {
        override var value3: String {
            return self.myValue4
        }
    
        var myValue4 = "4"
    }
    
    let myParent = PostCommentParent()
    let myChild = PostCommentChild()
    
    func parse(comment: PostComment) {
        print(comment.value3)
    }
    
    parse(comment: myChild)
    parse(comment: myParent)