0

I am trying to sort the NSMutableArray with this piece of code

let sortContacts = contactData! as NSArray as? [String]
        print("\(sortContacts.sort())") 

I am trying to convert the NSMutableArray to Array of String but when it comes to print("\(sortContacts.sort())") its giving me nil

Anyone who can suggest me sorting through NSMutableArray?

12
  • 1
    You can skip the as NSArray and just use as? [String] and then just use the Swift array sort method. It needs a closure that performs the comparison for sorting Commented Dec 5, 2016 at 11:34
  • @Paulw11 it shows me nil Commented Dec 5, 2016 at 11:38
  • Are you sure that contactData is an array of String? Commented Dec 5, 2016 at 11:40
  • if i print the value of contactData it shows me this "<Waev_Admin_4_0.ContactDB: 0x7a72e450>", "<Waev_Admin_4_0.ContactDB: 0x7a730e10>", "<Waev_Admin_4_0.ContactDB: 0x7a731170>", "<Waev_Admin_4_0.ContactDB: 0x7a7314d0>", "<Waev_Admin_4_0.ContactDB: 0x7a731830>", "<Waev_Admin_4_0.ContactDB: 0x7a731b60>", "<Waev_Admin_4_0.ContactDB: 0x7a731e70>", "<Waev_Admin_4_0.ContactDB: 0x7a7321a0>", "<Waev_Admin_4_0.ContactDB: 0x7a732500>", "<Waev_Admin_4_0.ContactDB: 0x7a7328a0>" Commented Dec 5, 2016 at 11:40
  • @Paulw11 in swift 2 still need to downcast to NSArray i think Commented Dec 5, 2016 at 11:42

2 Answers 2

1

The class NSMutableArray has several sort methods. You should read the documentation. One of the sort methods is this one.

By the way: a ! in Swift code is a code smell.

Sign up to request clarification or add additional context in comments.

Comments

0

This works, just make sure your NSMutableArray contains only string, else use if let:

let contactData = NSMutableArray(array: ["c","b","a"])
let sortContacts = contactData as NSArray as! [String]
print(sortContacts.sort())

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.