将一些 Objective-C 代码转换为 Swift

Converting some Objective-C code to Swift

我正在尝试将某些 Objective-C 代码转换为 Swift,但遇到了问题。

代码如下:

@property (nonatomic, strong) NSMutableDictionary* loadedNativeAdViews;
@synthesize loadedNativeAdViews;

...

loadedNativeAdViews = [[NSMutableDictionary alloc] init];

...

nativeAdView = [loadedNativeAdViews objectForKey:@(indexPath.row)];

我如何在 swift 中写这个?

NSDictionary 桥接到 Swift 原生 class Dictionary,因此您可以在 Objective-C 中使用 NSDictionary 的任何地方使用它。有关这方面的更多信息,请查看 Working with Cocoa Data Types 苹果文档。

Swift 是类型安全的,因此您必须指定要在字典中用作键和值的元素类型。

假设您使用 Int 作为键将 UIView 存储在字典中:

// 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]