[英]How to fix: Sorting method
Here is my method that handles sorting an array of strings这是我处理字符串数组排序的方法
func bucketNameGenerator(player1Id: String, player2Id: String) -> String {
var bucketName : String = ""
var uniqueBucketID = [String]()
uniqueBucketID = [player1Id, player2Id]
let sortedUniqueBucketID = uniqueBucketID.sorted(by: <)
bucketName = sortedUniqueBucketID.joined().replacingOccurrences(of: "$", with: "")
print("[bucketNameGenerator] bucketName: \(bucketName)")
return String(bucketName)
}
The two string values aren't pure strings they contain number values as well.这两个字符串值不是纯字符串,它们也包含数字值。 this way of sorting does not return the same value each time.
这种排序方式不会每次都返回相同的值。 Need suggestions on improvement here / directed down a path to create an asymmetric string each time.
需要改进这里的建议/每次都指向一条创建非对称字符串的路径。
Example Expected Results:
示例预期结果:
player1Id : 123jinrk1412941jdlndma
player2Id: 49812u4jldanec192hce12n
expected result both combined and sorted in an ascending order :
49812u4jldanec192hce12n123jinrk1412941jdlndma
The above example isn't correctly sorted but the goal is to get a string that is the same every-time the method runs with two inputted values.上面的示例没有正确排序,但目标是在每次使用两个输入值运行该方法时获得相同的字符串。
Calling sorted
for just two items is overkill.只为两个项目
sorted
的调用是矫枉过正的。
To consider numeric values compare
the strings with option numeric
要考虑数值,
compare
字符串与选项numeric
compare
func bucketNameGenerator(player1Id: String, player2Id: String) -> String {
let result : String
if player1Id.compare(player2Id, options: .numeric) == .orderedAscending {
result = player1Id + player2Id
} else {
result = player2Id + player1Id
}
return result.replacingOccurrences(of: "$", with: "")
}
Maybe you intended to use >
?也许您打算使用
>
?
func bucketNameGenerator(player1Id: String, player2Id: String) -> String {
let uniqueBucketID = [player1Id, player2Id]
let sortedUniqueBucketID = uniqueBucketID.sorted(by: >)
let bucketName = sortedUniqueBucketID.joined().replacingOccurrences(of: "$", with: "")
return bucketName
}
Or simpler :或者更简单:
func bucketNameGenerator(player1Id: String, player2Id: String) -> String {
let output = player1Id < player2Id ?
player2Id + player1Id : player1Id + player2Id
return output.replacingOccurrences(of: "$", with: "")
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.