2017-10-06 101 views
0
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) 

如何寫泛型函數,使其接受不同的模型和數據集?

+0

請告訴你如何設置與其他模型數據。如果代碼從模型到模型非常不同,我不建議將其用於通用。 – Sweeper

+0

每個模型從Basemodel繼承。所有模型都是基礎模型的子類,每個模型都有2-3種不同的屬性,也可以從基礎模型中獲得。 @Sweeper – Amey

+0

如果函數接受'ParentModel',它也接受所有的'Childs' – JuicyFruit

回答

1

如果我有這個想法沒錯,這裏是一個解決方案

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) 
+0

我有3類全部繼承BaseClass並需要提取和設置數據到所有類。所有3類有一些不同的變量彼此,我必須做一個通用的功能,接受模型,我通過並設置數據 – Amey

+0

@Amey抱歉,這是不可能理解,你是什麼意思。 – JuicyFruit

相關問題