NSDictionary
桥接到 Swift native class Dictionary
,所以你可以在任何你NSDictionary
在 Objective-C 中使用的地方使用它。有关这方面的更多信息,请查看使用 Cocoa 数据类型苹果文档。
Swift 是类型安全的,因此您必须指定用于键的元素类型和字典中的值。
假设您使用for 键将UIView
s 存储在 Dictionary 中:Int
// Declare the dictionary
// [Int: UIView] is equivalent to Dictionary<Int, UIView>
var loadedNativeAdViews = [Int: UIView]()
// Then, populate it
loadedNativeAdViews[0] = UIImageView() // UIImageView is also a UIView
loadedNativeAdViews[1] = UIView()
// You can even populate it in the declaration
// in this case you can use 'let' instead of 'var' to create an immutable dictionary
let loadedNativeAdViews: [Int: UIView] = [
0: UIImageView(),
1: UIView()
]
然后访问存储在字典中的元素:
let nativeAdView = loadedNativeAdViews[indexPath.row]