iPhone Guy iPhone Guy - 6 months ago 37
Swift Question

Swap array values in Swift

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.

Leo Leo
Answer
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())
    }
})