ios - 如何获取泛型类型类的大小(计数)?

标签 ios swift generics

我如何创建一个通用类,无论它是 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/

相关文章:

Ios Facebook SDK 我如何分享图片、链接、文本?

generics - 泛型类型的扩展方法,带有额外的泛型类型参数

java - 在 Java 中使用嵌套类实现 Iterable

java - 类 Class<T> 的泛型性质是什么意思?什么是T?

iphone - 如何防止在 phone-gap 中运行的应用程序垂直滚动?

ios - 在选择打印机之前获取空白 View

ios - 在 UICollectionView 中加载和显示随机单元格

ios - 长按结束 swift sprite kit 时如何运行函数

ios - UICollectionView 在 swift 2 中滚动时更改单元格数据

swift - 如何在 Swift 中创建通用闭包