Ricardo
Ricardo

Reputation: 8291

Swift 3 - How declare a typed NSMutableArray

I want to declare a dictionary with NSMutableArray<Client> values. But the thing is I'm getting an error whichs pointing me remove the <Client> part.

var mydict: [String:NSMutableArray<Client>] = [:]

How is the proper way for declare a typed NSMutableArray

Upvotes: 0

Views: 561

Answers (5)

Prashant Tukadiya
Prashant Tukadiya

Reputation: 16436

You should not to use NSMutableArray any more, However you can not achieve pass by ref with NSMutableArray Either for Clientif it is struct

Please use like below

 var myDict = [String : [Client]]()

If you want to pass by ref then Client should be a class in your implementation not struct .

If you want to go with struct only then you need to manually reassign updated Client` to dictionary back

in case of Class (Better option)

(myDict["key1"] as! [Client]).firstName = "Jon"

in case of Struct

    var clientObjArray =  (myDict["key1"] as! [Client])
    var clientObjArrayFirstObj =  clientObjArray.first
    clientObjArrayFirstObj?.name =  "Jon"
    clientObjArray.remove(at: 0)
    clientObjArray.insert(clientObjArrayFirstObj!, at: 0)
    myDict["key1"] = clientObjArray

Note: For example I have added first and 0 Index static

Hope it is clear to you

Upvotes: 0

Damo
Damo

Reputation: 12890

A quick expansion on Vishal Patel's answer:

If you paste this into a storyboard it will fail on none Client types

import UIKit
import PlaygroundSupport

struct Client
{

}

struct NoneClient
{

}

class MyViewController : UIViewController {

    var mydict: [String:[Client]] = [:]

    override func loadView() {
        let client = Client()
        mydict["xyz"] = [client]

        let noneClient = NoneClient()

        mydict["abc"] = [NoneClient]
    }
}

Upvotes: 1

Vishal Patel
Vishal Patel

Reputation: 507

You can also write like this var mydict: [String:[Client]] = [:]

You can do like this

import UIKit
import PlaygroundSupport

    struct Client
    {

    }
    class MyViewController : UIViewController {

        var mydict: [String:[Client]] = [:]

        override func loadView() {
            let client = Client()
            mydict["xyz"] = [client]
            print(mydict)
        }
    }

Upvotes: 0

yasirmturk
yasirmturk

Reputation: 1954

NSMutableArray is a heterogeneous container

Upvotes: 1

maxkoriakin
maxkoriakin

Reputation: 337

var myDict = [String : [Client]]()

Upvotes: 0

Related Questions