gpt4 book ai didi

ios - 在 Swift 中交换数组值

转载 作者:行者123 更新时间:2023-11-28 13:20:03 27 4
gpt4 key购买 nike

我在包含字符串数字(作为字符串)的数组中有3个元素

例如,数组包含如下元素

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

排序后变成

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

我想把字符串放在最前面,数字放在最后。

预期的输出应该是

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

如何交换数组元素。

注意如果数组有多个字符串和数字(​​字符串如"1","2")。字符串(单词或字符)应在前,数字(应按升序排列)在后。

到目前为止我试过了。

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

返回结果为 "1","2","3","abc"

但预期的输出应该是 "abc","1","2","3"。如何交换数组中的对象。

最佳答案

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
}
}

这应该是工作结果是“abc” “def” “1” “2” “3”

如果结果 abc 3 2 1 没问题,就用这个

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

这个结果是 "def""abc""3""2""1"

更新:

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

关于ios - 在 Swift 中交换数组值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26668816/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com