Jonathan Allen Grant
Jonathan Allen Grant

Reputation: 3668

Swift: Could not find member init for my NSDictionary

I am making a NSDictionary to hold data for a tableview. The tableview is like a contacts list, with contacts separated by first name and sorted alphabetically, so I am making a dictionary to hold these contacts. The dictionary is defined as [String: [User]]() where User is my own object.

However, when I check to see if there are any entries for the first letter in a user's first name, I get the compile error: Could not find member init on my code.

Here is my code:

var users = CurrentAccount.friends
var organizedUsers = [String: [User]]()

func organizeFriendsByFirstName() {
    for user in users {
        if let xc = organizedUsers["\(user.firstName!.substringToIndex(1))"] {

        } else {
            organizedUsers["\(user.firstName!.substringToIndex(1))"] = [user]
        }
    }
}

Upvotes: 2

Views: 162

Answers (1)

Victor Sigler
Victor Sigler

Reputation: 23449

You error not have anything to do with your NSDictionary, sometimes the Swift compiler it's not accurate with its compile errors, see this nice article Swift Compiler Diagnostics.

If you put outside the line user.firstName!.substringToIndex(1) this throws the compile error :

Cannot invoke 'substringToIndex' with an argument list of type '(Int)'.

And it is the cause of your error, you can use the advance function to make indexes in an String, change your function to the following:

func organizeFriendsByFirstName() {
    for user in users {

        if let xc = organizedUsers["\(user.firstName!.substringToIndex(advance(user.firstName!.startIndex, 1)))"] {

        } else {
           organizedUsers["\(user.firstName!.substringToIndex(advance(user.firstName!.startIndex, 1)))"] = [user]
        }
    }
}

I hope this help you.

Upvotes: 2

Related Questions