繁体   English   中英

如何在Swift中放入Array的第一个和最后一个元素

[英]How to put the of first and last element of Array in Swift

我有这样的字典

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

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

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

通过使用Array.firstArray.last方法,我将获得我的数组的第一个元素和最后一个元素的值。

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

但我真正想要的是我想从第一去年$ 00.00$ 800至使所需组合[$点- $ 800.00。

我怎样才能做到这一点。 请帮忙?

您需要取first值( "$00.00 - $200.00" ),然后取last值( "$600.00 - $800.00" ),然后用“ - ”符号拆分它们,分别取第一个和最后一个值并将它组合成单个字符串。

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)"

为了更好的选项处理你可以使用它( 注意 ,我正在遵循我的描述性编码风格。这段代码可以更加紧凑)

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"])

过去上面的代码到操场。 它可以用更短的方式编写,但为了描述,我保持这样

您可以执行以下操作:

  let r = ["$00.00 - $200.00", "$200.00 - $400.00", "$600.00 - $800.00"]
          .reduce("", +) //Combine all strings
          .components(separatedBy: " - ") //Split the result
          .map({ String($0) }) //Convert from SubString to String
    print(r.first) //prints $00.00
    print(r.last) // prints $800.00

let newRange = [r.first!, r.last!].joined(separator: " - ")
func priceRange(with priceRanges: [String]) -> String? {
    guard
        let min = priceRanges.first?.components(separatedBy: " - ").first,
        let max = priceRanges.last?.components(separatedBy: " - ").last else { return nil }

    return "[\(min) - \(max)]"
}

print(priceRange(
    with: [
        "$00.00 - $200.00",
        "$200.00 - $400.00",
        "$600.00 - $800.00"
    ]
))

您可以使用split来基于-字符拆分范围,而不是删除空格。

let first = priceRange.first?.split(separator: "-").first?.trimmingCharacters(in: .whitespaces) ?? ""
let last = priceRange.last?.split(separator: "-").last?.trimmingCharacters(in: .whitespaces) ?? ""
let amountsArray = ["$00.00 - $200.00", "$200.00 - $400.00", "$600.00 - $800.00"]
let amounts = amountsArray.reduce("") { $0 + $1 }.split(separator: "-")
if let first = amounts.first, let last = amounts.last {
    print("[\(first)-\(last)]")
}

使用此您可以找到您的值:

if let obj = priceRange as? [String] {
    let max = priceRange.max()
    let min = priceRange.min()
    print(max?.components(separatedBy: " - ").map({$0.trimmingCharacters(in: .whitespacesAndNewlines)}).max())  //800
    print(min?.components(separatedBy: " - ").map({$0.trimmingCharacters(in: .whitespacesAndNewlines)}).min())   //00
}

//使用组件(separatedBy :):

让price = f.components(separatedBy:“ - ”)

price.first // $ 600.00

prices.last // $ 800.00

您还可以使用String.components(separatedBy :):

var text = "100$ - 200$"
var new = text.components(separatedBy: " - ")[0]
print(new) // Prints 100$

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM