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

时间:2015-11-05 12:06:03

标签: objective-c swift mobfox

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

下面是代码:

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

...

loadedNativeAdViews = [[NSMutableDictionary alloc] init];

...

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

我如何在swift中写这个?

1 个答案:

答案 0 :(得分:1)

Dictionary桥接到Swift本机类NSDictionary,因此您可以在Objective-C中使用UIView的任何位置使用它。有关此问题的详细信息,请查看Working with Cocoa Data Types apple docs。

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

假设您使用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]

然后访问存储在字典中的元素:

{{1}}