Ios 如何为不同的类编写通用函数?
用法:Ios 如何为不同的类编写通用函数?,ios,iphone,swift,generic-programming,Ios,Iphone,Swift,Generic Programming,用法: 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
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
}
如何编写通用函数,以便它接受不同的模型并设置数据?如果我的想法正确,下面是一个解决方案
cellComment.setPostcommentData(postmodel: model1,index:indexPath)
cellComment.setPostcommentData(postmodel: model2,index:indexPath)
cellComment.setPostcommentData(postmodel: model3,index:indexPath)
请说明如何使用其他型号设置数据。如果代码在不同的模型之间有很大的差异,我不建议将其设置为泛型。每个模型都继承自Basemodel。所有模型都是basemodel的子类,每个模型都有2-3个与basemodel不同的属性@Sweeperif函数接受ParentModel,它也接受所有的ChildsChild,还有一些与ParentModel不同的变量。还需要在泛型函数中访问该变量@JuicyFruit@Amey对不起,这是不可能理解的,你是什么意思。
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)