簡體   English   中英

Swift中的非可選類型不應該包含可選嗎?

[英]Shouldn't an optional be inclusive to a non-optional type in Swift?

更新:完整代碼

我有以下代碼:

struct Set<T : Hashable>: Sequence {
    var items: Dictionary<Int, T> = [:]

    func append(o: T?) {
        if let newValue = o {
            items[newValue.hashValue] = newValue
        }
    }

    func generate() -> TypeGenerator<T> {
        return TypeGenerator ( Slice<T>( items.values ) )
    }
}

我得到錯誤:

找不到接受提供的參數的“下標”的重載。

對於該行:

items[newValue.hashValue] = newValue

據我了解,這是因為newValue的類型是T而不是T? ,這表示它不是可選的。 這是因為Dictionary用於訪問鍵/值對的subscript定義為

subscript (key: KeyType) -> ValueType?

表示只能接受可選值。 在我的情況下, newValue在驗證后不是nil不是可選的。

但是,不是包括非可選的可選內容嗎? 類型不是可選類型+ nil嗎?

為什么可以接受所有內容+ nil東西會拒絕不能為nil的類型?

hashValue 說明:我檢查o是否為nil的原因是能夠調用其hashValue ,而該hashValue不能直接從可選或未包裝的可選中訪問( o!.hashValue引發編譯錯誤)。

我也不能用

items[newValue.hashValue] = o

因為它已驗證o不是值得分配的可選值,即使它不允許訪問其hashValue屬性。

字典未定義為存儲可選值。 只是賦值運算符接受一個可選值,因為為其賦予nil將從字典中刪除整個鍵。

您遇到的問題是您試圖以非變異方法變異您的屬性items 您需要將您的方法定義為變異:

mutating func append(o: T?) {
    if let newValue = o {
        items[newValue.hashValue] = newValue
    }
}

將可選變量分配給非可選值當然沒有問題:

var optionalString : String? = "Hello, World"

以同樣的方式,將字典的鍵分配給非可選值是完全有效的:

var items : [Int:String] = [:]
items[10] = "Hello, World"

然后,您可以將鍵分配為nil,以從字典中完全刪除鍵:

items[10] = nil

另外,我認為您對hashValue是什么以及如何使用它有根本的誤解。 您不應將hashValue的值作為鍵傳遞給字典。 字典對您提供的值調用hashValue,因此您使字典采用hashValue的hashValue。

無法保證hashValue會與所有其他具有不同值的hashValue不同 換句話說,“ A”的哈希值可以是與“ B”相同的哈希值。 字典足夠復雜,可以處理這種情況,並且仍然可以為您提供特定鍵的正確值,但是您的代碼無法處理該鍵。

實際上,您可以將非可選值存儲在Dictionary並且通常,只要有T?就可以傳遞T類型的對象T? 是期待。

真正的問題是您還沒有告訴編譯器T是可Hashable

您必須使用T: HashableT施加類型約束。 您可以在類級別執行此操作(我想此方法位於通用類內部),就像這樣

class Foo<T: Hashable> {
    var items: Dictionary<Int, T> = [:]
    func append(o: T?) {
        if let newValue = o {
            items[newValue.hashValue] = newValue
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM