-1

我试图将一些 Objective-C 代码转换为 Swift,但遇到了麻烦。

继承人的代码:

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

...

loadedNativeAdViews = [[NSMutableDictionary alloc] init];

...

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

我将如何快速写这个?

4

1 回答 1

1

NSDictionary桥接到 Swift native class Dictionary,所以你可以在任何你NSDictionary在 Objective-C 中使用的地方使用它。有关这方面的更多信息,请查看使用 Cocoa 数据类型苹果文档。

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

假设您使用for 键将UIViews 存储在 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]
于 2015-11-05T12:13:24.190 回答