× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

How can i sort/filter an NSArray for the following needs?

Antonio Bello
Apr 22, 2015
<p>I recommend using the Swift Array type rather than <code>NSArray</code>, and using <code>filter</code> combined with the <code>sort</code> method, which takes a closure determining the sort order of 2 elements.</p> <p>In your case, it would be implemented as:</p> <pre><code>var candidates = ["Berlin-Lichtenberg", "Berlin-Lichterfelde Ost", "Berlin-Lichterfelde West", "Braunsdorf-Lichtenwalde", "Darmstadt-Lichtwiese", "Lichtenberg (Erzgeb)", "Lichtenfels", "Lichtenrade", "Lichtenstein (Sachs)", "Lichtentanne (Sachs)", "Lichtentanne (Thür)", "Lichtenthal", "Lichterfelde Süd", "Rostock Lichtenhagen", "Hamburg", "München", "Köln", "Bonn"] let root = "Licht" var results = candidates.filter { $0.rangeOfString(root) != nil }.sorted { (lhs: String, rhs: String) -&gt; Bool in if startsWith(lhs, root) { if (startsWith(rhs, root)) { // Both start with root, so return the string comparison return lhs &lt; rhs } // lhs starts with root, rhs doesn't, so lhs comes first return true } // rhs starts with root, lhs doesn't, so rhs comes first if (startsWith(rhs, root)) { return false } // return the normal string comparison return lhs &lt; rhs } </code></pre> <p>This tip was originally posted on <a href="http://stackoverflow.com/questions/29670125/How%20can%20i%20sort/filter%20an%20NSArray%20for%20the%20following%20needs?/29670550">Stack Overflow</a>.</p>
comments powered by Disqus