简体   繁体   中英

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

I have a dictionary like this

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

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

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?

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

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

You can do the following:

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

You can use split to split up the range based on the - character than remove the whitespaces.

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

Use this You can find your values:

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
}

//use components(separatedBy:) :

let prices = f.components(separatedBy: " - ")

prices.first // $600.00

prices.last // $800.00

You could also use String.components(separatedBy:):

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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