泛型 – 使用Swift语言的自定义对象的泛型类型

泛型 – 使用Swift语言的自定义对象的泛型类型,第1张

概述我想知道有没有办法在下面的泛型函数中比较两个泛型类型实例与==运算符: func compare<T>(T a, T b) -> Bool { if a == b{ // do something return true; }else{ // do another thing return false; } 我想知道有没有办法在下面的泛型函数中比较两个泛型类型实例与==运算符:
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 Developer Resources,

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 truevalue2.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}
总结

以上是内存溢出为你收集整理的泛型 – 使用Swift语言的自定义对象的泛型类型全部内容,希望文章能够帮你解决泛型 – 使用Swift语言的自定义对象的泛型类型所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/1029452.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-23
下一篇 2022-05-23

发表评论

登录后才能评论

评论列表(0条)

保存