2015-11-05 62 views
-1

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

继承人的代码:

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

... 

loadedNativeAdViews = [[NSMutableDictionary alloc] init]; 

... 

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

我怎么会写这篇文章迅速?

回答

1

NSDictionary桥接到斯威夫特本机类Dictionary,所以无论你在Objective-C使用NSDictionary你可以使用它。有关详细信息,请参阅Working with Cocoa Data Types apple文档。

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

假设你使用Int该键上的字典存储UIView S:

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