0

I have 3 elements in the array which contains strings and numbers(as strings)

for eg, array contain elements like

 var elementArray:NSArray //"3","2","1","abc"

After sorting it becomes

var sortedArray = //"1","2","3","abc"

I want to make a string as first and the numbers in the last.

Expected output should be

var sortedArray = //"abc","1","2","3"

How can I swap the array elements.

Note that if array has multiple strings and numbers(strings like "1","2"). The strings(words or characters) should be come first and the numbers (which should be in ascending order)comes last.

so far I tried this.

 var sortedArray:NSArray = array.sortedArrayUsingComparator({(item1:AnyObject!, item2:AnyObject!) -> NSComparisonResult in
 let comparisonOptions:NSStringCompareOptions =
 NSStringCompareOptions.CaseInsensitiveSearch |
 NSStringCompareOptions.NumericSearch |
 NSStringCompareOptions.WidthInsensitiveSearch |
 NSStringCompareOptions.ForcedOrderingSearch;
 var str1:String = (item1 as String)
 var str2:String = (item2 as String)
 return str1.compare(str2, options: comparisonOptions, range: str1.startIndex ..< str1.endIndex, locale: NSLocale.currentLocale())
 })

which returns result as "1","2","3","abc".

But the expected output should be "abc","1","2","3". How can I exchange object in the array.

Dharmesh Kheni
71.9k33 gold badges163 silver badges166 bronze badges
asked Oct 31, 2014 at 6:39
1
  • Maybe you could try extracting all the numbers from the source array into a new array, sort them, then extra all the words from the source array into a new array, sort them, finally combine the two new arrays into one last array, adding in all the sorted words first, then add in all the sorted numbers aftewards. You would need to check if the element in the source array contains any characters (so you can identify if it's a proper number). Commented Oct 31, 2014 at 6:47

3 Answers 3

1
var elementArray = ["1","2","3","abc","def"]
sort(&elementArray){
 if 0ドル.toInt() != nil && 1ドル.toInt() != nil{
 return 0ドル < 1ドル
 }
 else if 0ドル.toInt() == nil && 1ドル.toInt() == nil{
 return 0ドル < 1ドル
 }
 else
 {
 return 0ドル > 1ドル
 }
}

This should be work Result is "abc" "def" "1" "2" "3"

If result abc 3 2 1 is OK,just use this

var elementArray = ["1","2","3","abc","def"]
 sort(&elementArray,>)

this result is "def" "abc" "3" "2" "1"

Update:

var elementArray:NSArray = ["1","2","3","abc","def"]
var sortedArray:NSArray = elementArray.sortedArrayUsingComparator({(item1:AnyObject!, item2:AnyObject!) -> NSComparisonResult in
 let comparisonOptions:NSStringCompareOptions =
 NSStringCompareOptions.CaseInsensitiveSearch |
 NSStringCompareOptions.NumericSearch |
 NSStringCompareOptions.WidthInsensitiveSearch |
 NSStringCompareOptions.ForcedOrderingSearch;
 var str1:String = (item1 as String)
 var str2:String = (item2 as String)
 if str1.toInt() != nil && str2.toInt() != nil{
 return str1.compare(str2, options: comparisonOptions, range: str1.startIndex ..< str1.endIndex, locale: NSLocale.currentLocale())
 }
 else if str1.toInt() == nil && str2.toInt() == nil{
 return str1.compare(str2, options: comparisonOptions, range: str1.startIndex ..< str1.endIndex, locale: NSLocale.currentLocale())
 }
 else
 {
 return str2.compare(str1, options: comparisonOptions, range: str1.startIndex ..< str1.endIndex, locale: NSLocale.currentLocale())
 }
})
answered Oct 31, 2014 at 6:53
3
  • Thanks for your answer. i am using NSArray, because i want to sort NSMutableDictionary keys. how can i use the above method in NSArray? Commented Oct 31, 2014 at 6:59
  • See codes in update,i update it from your code.Because,i am not familiar with sort NSArray.It works well on my playground Commented Oct 31, 2014 at 7:18
  • Using Swift's sort (or sorted) should actually work fine, you just have to cast elementArray to [String] first (you can cast back to NSArray if that's what you need). However, the sort comparison function as written here is going to sort the numbers lexicographically and not numerically, so that would have to be tweaked a little. Commented Oct 31, 2014 at 14:29
1

Here is a way to add swap capability to Swift Array:

public extension Array {
 mutating func swap(ind1: Int, _ ind2: Int){
 var temp: Element
 temp = self[ind1]
 self[ind1] = self[ind2]
 self[ind2] = temp
 }
}

Now, you can use this as follow:

let myArray = [[1], 2, "3"]
myArray.swap(0,2) // ["3", 2, [1]]
answered May 18, 2016 at 10:47
0

Swapping array values is easy:

var elementArray = ["1","2","3","abc","def"]
elementArray.swapAt(0, 3)
elementArray.swapAt(1, 4)
print(elementArray) // ["abc", "def", "3", "1", "2"]

Sorting literals before numbers:

elementArray = ["1","2","3","abc","def"]
elementArray.sort {
 if [0,ドル 1ドル].allSatisfy({ Int(0ドル) != nil}) || [0,ドル 1ドル].allSatisfy({ Int(0ドル) == nil}) {
 return 0ドル < 1ドル
 } else
 {
 return 0ドル > 1ドル
 }
}
print(elementArray) // ["abc", "def", "1", "2", "3"]
answered Feb 22, 2022 at 9:15

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.