gpt4 book ai didi

ios - 1 个全局函数或多个实例函数

转载 作者:搜寻专家 更新时间:2023-11-01 05:49:56 24 4
gpt4 key购买 nike

如果有两个相似的类需要相同的功能。是全局编写函数更好,还是在每个类中两次编写相同的函数。例如。

选项 1:两个实例函数

class A {

func buttonTapped() {
upvote(id)
}

func upvote(postID:String) {
// upvote the post
}
}

class B {

func buttonTapped() {
upvote(id)
}

func upvote(postID:String) {
// upvote the post
}
}

选项 2:一个全局函数

class A {
func buttonTapped() {
upvote(id)
}
}

class B {
func buttonTapped() {
upvote(id)
}
}

func upvote(postID:string) {
// upvote the post
}

或者有更好的选择吗?

最佳答案

我都不建议。

您应该有一个数据模型类,upvote 函数应该是该类的一部分。

class Post {
var postID: String
public private(set) var votes: Int

...

func upvote() {
self.votes += 1
}
}

那么你会称它为

 somePost.upvote()

关于ios - 1 个全局函数或多个实例函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44619654/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com