努力實作以下2)。
在下面的例子中,T是一個具體的型別。T可能是String,但這些例子看起來會更奇怪。
作品:
var v = [ // v is a Dictionary with two Dictionary<String, T>.Element's "x": T("x"), // Unfortunate since "x" has to be repeated "y": T("y") ]所需的語法,旨在與 1) 相同。不作業:
var v = [ { let s = "x"; // Attempting to use a closure to "inline" the local variable s return (s: T(name: s)) // Using a tuple to return the Dictionary<String, T>.Element }(), { let s = "y"; return (s: T(name: s)) }() ]
2) 的 Xcode 錯誤:只能將異構集合文字推斷為“[Any]”;如果這是故意的,請添加顯式型別注釋
嘗試使用顯式型別修復 2)。不作業。
var v : Dictionary<String, T>.Element = [ { let s = "x"; return Dictionary<String, T>.Element(s: T(name: s)) }(), { let s = "y"; return Dictionary<String, T>.Element(s: T(name: s)) }() ]
3) 的 Xcode 錯誤:'Dictionary<String, T>' 型別的字典不能用陣列字面量初始化
誠然,這個“MWE”示例看起來很奇怪,但我試圖理解,一般來說,它可能如何使用字典元素(鍵和值一起,作為一個洞),就好像它是(非正式地說)一個元素陣列。我的理解可能完全有缺陷。但是,以下是一個有效的示例:
與上面不同,但有效:
var v = [ Dictionary<String, T>.Element(key: "x", value: T("x")) ]
編輯。
這也有效:
var v = Dictionary<String, T>(uniqueKeysWithValues: [ { let s = "x"; return (s, T("x")) }() ] )
所以我現在得出的結論是,這種樸素陣串列示法背后的“邏輯”不起作用,是你必須明確唯一的鍵......為什么你需要這種明確性,但是,我不明白。
uj5u.com熱心網友回復:
如果你有一個鍵陣列,并且你想通過將每個鍵映射到另一種型別來創建一個字典,我建議這樣:
let keys = ["x", "y", "z"]
let dict = Dictionary(
uniqueKeysWithValues: keys.map { key in (key, T(key)) }
)
uj5u.com熱心網友回復:
我仍然不確定你到底想要什么,但我想我添加了這個解決方案,看看它是否正確,或者至少有什么需要進一步討論的
struct T {
let name: String
}
extension Dictionary where Key == String, Value == T {
init(values: Key...) {
self = values.reduce(into: [:]) { $0[$1] = T(name: $1) }
}
}
var dict = Dictionary(values: "x", "y")
init當需要動態時的替代解決方案
extension Dictionary where Key == String, Value == T {
init(values: Key..., construct: (Key) -> T) {
self = values.reduce(into: [:]) { $0[$1] = construct($1) }
}
}
var dict = Dictionary(values: "x", "y") { T(name: $0)}
uj5u.com熱心網友回復:
足夠的解決方案:
var v = Dictionary<String, T>(uniqueKeysWithValues:
[ { let s = "x"; return (s, T("x")) }(),
{ let s = "y"; return (s, T("y")) }(),
]
)
這意味著,您必須使用顯式Dictionary建構式,使用uniqueKeysWithValues
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/496989.html
上一篇:呼叫text.flatMap(URL.init)的目的是什么?
下一篇:swift“maximumLengthOfBytes(using:)”和“lengthOfBytes(using:)”有什么區別
