如何在Swift中将Array的第一个和最后一个元素放入 [英] How to put the of first and last element of Array in Swift

查看:604
本文介绍了如何在Swift中将Array的第一个和最后一个元素放入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的字典

["Price": ["$00.00 - $200.00", "$200.00 - $400.00", "$600.00 - $800.00"]]

现在我将所有字典值存储在这样的数组中

Now I am storing all the dictionary value in array like this

var priceRange: [String] = [String]()
if let obj = currentFilters["Price"] as? [String] {
        self.priceRange = obj
        printD(self.priceRange)
    }

然后使用 Array.first Array.last 方法,数组的第一个元素和最后一个元素的值。

And by the use of Array.first and Array.last method I will get the values of first element and last element of my array.

let first = priceRange.first ?? "" // will get("[$00.00 - $200.00]")
let last = priceRange.last ?? ""   // will get("[$600.00 - $800.00]")

但是我真正想要的是我希望来自 first $ 00.00 和来自 last $ 800 进行所需的 [$ 00.00- $ 800.00]

But What I actually want is I want the $00.00 from first and $800 from last to make the desired combination of [$00.00 - $800.00].

我该怎么做。请帮忙?

How can I do this. Please help?

推荐答案

您需要先获取 值( $ 00.00-$ 200.00 ),然后最后一个值( $ 600.00-$ 800.00 ),然后用 -符号将它们分开,分别取第一个和最后一个值,并将其组合为单个字符串。

You need to take first value ("$00.00 - $200.00"), then last value ("$600.00 - $800.00"), then split them by "-" symbol and take first and last values respectively and combine it to single string.

let currentFilters = ["Price": ["$00.00 - $200.00", "$200.00 - $400.00", "$600.00 - $800.00"]]

var priceRange: [String] = [String]()
if let obj = currentFilters["Price"] as? [String] {
    priceRange = obj
    print(priceRange)
}

let first = priceRange.first!.split(separator: "-").first!
let last = priceRange.last!.split(separator: "-").last!

let range = "\(first) - \(last)"

为了更好地处理可选内容,您可以使用此代码( NB ,我遵循我的描述性编码风格。该代码可以更紧凑)

For better optionals handling you can use this (NB, I'm following my over-descriptive coding style. This code can be much more compact)

func totalRange(filters: [String]?) -> String? {
    guard let filters = filters else { return nil }
    guard filters.isEmpty == false else { return nil }
    guard let startComponents = priceRange.first?.split(separator: "-"), startComponents.count == 2 else {
        fatalError("Unexpected Filter format for first filter") // or `return nil`
    }
    guard let endComponents = priceRange.last?.split(separator: "-"), endComponents.count == 2 else {
        fatalError("Unexpected Filter format for last filter") // or `return nil`
    }
    return "\(startComponents.first!) - \(endComponents.last!)"
}
let range = totalRange(filters: currentFilters["Price"])

let range1 = totalRange(filters: currentFilters["Not Exists"])

将上面的代码粘贴到操场。它可以写得更短一些,但是为了描述方便,我还是这样保留它

Past the code above to the playground. It can be written much shorter way, but I kept it like that for the sake of descriptivity

这篇关于如何在Swift中将Array的第一个和最后一个元素放入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆