【问题标题】:Cannot subscript a value of type 'Self' with an index of type 'Int'无法使用“Int”类型的索引为“Self”类型的值下标
【发布时间】:2018-04-10 12:07:21
【问题描述】:

尝试在 Swift 中扩展 Collection 时,我不断收到以下错误:

不能用“Int”类型的索引为“Self”类型的值下标

这是我的代码:

extension Collection {
    func random() -> Element {
        let randomIndex = count.arc4random
        return self[randomIndex]
    }
}

【问题讨论】:

    标签: swift


    【解决方案1】:

    Collectionsubscript 方法需要 Self.Index,而不是 Int

    你需要:

    return self[self.index(self.startIndex, offsetBy: randomIndex)]
    

    【讨论】:

    • 不要忘记isEmpty 检查。只是为了安全
    • @staticVoidMan 这将是对 OP 方法的一个很好的增强。但这也意味着他们的random 方法需要返回一个可选的Element
    • @staticVoidMan 我在代码中使用它的方式,不应该有一个空集合。既然是这种情况,最好在我的扩展中添加assert(count > 0, "Collection must not be empty") 语句吗?
    • assert(!isEmpty, "...").
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多