Search code examples
objective-cswiftmobfox

Converting some Objective-C code to Swift


Im trying to convert some Objective-C code to Swift but having trouble with it.

Heres the code:

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

...

loadedNativeAdViews = [[NSMutableDictionary alloc] init];

...

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

How would I write this in swift?


Solution

  • NSDictionary is bridged to Swift native class Dictionary, so you can use it wherever you used NSDictionary in Objective-C. For more information about this, take a look at Working with Cocoa Data Types apple docs.

    Swift is type safe, so you have to specify the kind of elements that you are using for the key and the value in the dictionary.

    Assuming you are storing UIViews on a Dictionary using Int for the key:

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

    Then access the elements stored in the dictionary:

    let nativeAdView = loadedNativeAdViews[indexPath.row]