我如何创建一个通用类,无论它是 Int、String 等,我都可以在其中获取项目的大小(或计数)...
class Node<T: Equatable> {
var item: T? = nil
var next: Node? = nil
init(item:T, node:Node?) {
self.item = item
self.next = node
}
var count:Int { <-------------- this is what I need to fix
return item.count
}
}
我想这样做,这样我就可以像这样比较项目:
let one = Node<Int>(item:1, node:nil)
let two = Node<Int>(item:2, node:nil)
return one.count < two.count <--------- should return true
let str1 = Node<String>(item:"moose", node:nil)
let str2 = Node<String>(item:"cow", node:nil)
return str1.count < str2.count <------- should return false
更新 我现在遇到了正常比较的问题。我收到错误消息,“二元运算符‘==’不能应用于‘Any’和‘Any?’类型的操作数。” (又名“协议(protocol) <>”)”
func search(item:Any) -> Bool {
var current:Node? = self.head
var found = false
while current != nil && found != true {
if current?.item == item { <---------this is the error line
found = true
} else {
current = current?.next
}
}
return found
}
除了用于节点比较的运算符之外,我还尝试实现一个自定义的“==”运算符
func ==(lhs: Node, rhs: Node) -> Bool {
return lhs.count == rhs.count
}
func ==(lhs: Any, rhs: Any) -> Bool {
return lhs == rhs
}
最佳答案
您只需要使您的 Node 类符合 Equatable 和 Comparable,并将您的项目类型更改为 Any?:
class Node: Equatable, Comparable {
var item: Any? = nil
var next: Node? = nil
init(item: Any?, node: Node?) {
self.item = item
self.next = node
}
var count: Int {
// the trick is here, just conditionally casting to Int or String and return its Int value or the string characters count.
if let val = item as? Int {
return val
}
if let str = item as? String {
return str.characters.count
}
return 0
}
}
func ==(lhs: Node, rhs: Node) -> Bool {
return lhs.count == rhs.count
}
func <(lhs: Node, rhs: Node) -> Bool {
return lhs.count < rhs.count
}
用法:
let nodeOne = Node(item:1, node:nil)
let nodeTwo = Node(item:2, node:nil)
print(nodeOne < nodeTwo) // true
let nodeStr1 = Node(item:"moose", node:nil)
let nodeStr2 = Node(item:"cow", node:nil)
print( nodeStr1 < nodeStr2) // false
关于ios - 如何获取泛型类型类的大小(计数)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39584514/