gpt4 book ai didi

arrays - 自定义字符串排序: How do I place these strings in an array in this particular order

转载 作者:行者123 更新时间:2023-11-30 10:01:47 25 4
gpt4 key购买 nike

/*你好,我是 swift 的新手,并且在自定义数组排序上遇到了困难。如何按特定顺序将这些字符串放入数组中?

相机:Prime:滤镜:支持:

如果我使用 NSString,我可以使用 .containsString我想要一个动态数组,因为我不知道列表最终会有多大

感谢您百忙之中看我的问题!*/

var equipmentList:[String]  = []

var item1 = NSString(string: "Support: Fluid Head ")

var item2 = NSString(string: "Prime: Ziess Master Primes")

var item3 = NSString(string: "Filter: ND Set")

var item4 = NSString(string: "Camera: Arri Alexa")



if item1.containsString("Camera:") {

// place in first position in a dynamic array

}

if item1.containsString("Prime:") {

// place in second position in a dynamic array

}

if item1.containsString("Filter:") {

// place in third position in a dynamic array

}

if item1.containsString("Support:") {

// place in forth position in a dynamic array

}

最佳答案

尝试一下。解释在评论中:

// The order by which you will sort your equipment types
let order = ["Camera", "Prime", "Filter", "Support"]


// The sorting function
func compareEquipment(equipment1: String, equipment2: String) -> Bool {
let components1 = equipment1.componentsSeparatedByString(":")
let components2 = equipment2.componentsSeparatedByString(":")

// Each equipment string must have exactly 2 components separeted by
// a colon (:), like in this format:
// equipment type: eqipment name
//
// If not, quit the function reporting an error
guard components1.count == 2 && components2.count == 2 else {
fatalError("Invalid equipment: '\(equipment1)' or '\(equipment2)'")
}

// The order of the equipment type
let order1 = order.indexOf(components1.first!) ?? Int.max
let order2 = order.indexOf(components2.first!) ?? Int.max

// When comparing 2 equipment strings, order them by equipment type
// first. If they are of the same type, order them by name
if order1 != order2 {
return order1 < order2
} else {
return components1.last! < components2.last
}
}


let equipmentList = [
"Support: Fluid Head",
"Prime: Ziess Master Primes",
"Filter: ND Set",
"Camera: Arri Alexa"
]

let sortedEquipmentList = equipmentList.sort(compareEquipment)

print(sortedEquipmentList)

关于arrays - 自定义字符串排序: How do I place these strings in an array in this particular order,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38111751/

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