gpt4 book ai didi

generics - Swift 语言中具有自定义对象的通用类型

转载 作者:搜寻专家 更新时间:2023-10-30 22:06:07 24 4
gpt4 key购买 nike

我想知道是否有任何方法可以在以下泛型函数中使用 == 运算符比较两个泛型类型实例:

 func compare<T>(T a, T b) -> Bool {
if a == b{
// do something
return true;
}else{
// do another thing
return false;
}
}

这是我的自定义对象:

class MyObj{
var id = 3
var name: String?
}

最佳答案

来自 Apple 开发者资源,

Not every type in Swift can be compared with the equal to operator (==). If you create your own class or structure to represent a complex data model, for example, then the meaning of “equal to” for that class or structure is not something that Swift can guess for you. Because of this, it is not possible to guarantee that this code will work for every possible type T, and an appropriate error is reported when you try to compile the code.

All is not lost, however. The Swift standard library defines a protocol called
Equatable, which requires any conforming type to implement the equal to operator (==) and the not equal to operator (!=) to compare any two values of that type. All of Swift’s standard types automatically support the Equatable protocol.

Any type that is Equatable can be used safely with the findIndex function, because it is guaranteed to support the equal to operator. To express this fact, you write a type constraint of Equatable as part of the type parameter’s definition when you define the function:

func findIndex<T: Equatable>(array: T[], valueToFind: T) -> Int? {
for (index, value) in enumerate(array) {
if value == valueToFind {
return index
}
}
return nil
}

这是他们文档中的一个示例,解释了如何覆盖 ==

struct MyStruct: Equatable {
var name = "Untitled"
}
func == (lhs: MyStruct, rhs: MyStruct) -> Bool {
return lhs.name == rhs.name
}

let value1 = MyStruct()
var value2 = MyStruct()
let firstCheck = value1 == value2
// firstCheck is true

value2.name = "A New Name"
let secondCheck = value1 == value2
// secondCheck is false

在你的情况下你会这样做,

class MyObj{
var id = 3
var name: String?
}

func == (lhs: MyObj, rhs: MyObj) -> Bool {
return lhs.id == rhs.id
}

关于generics - Swift 语言中具有自定义对象的通用类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24019076/

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