Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

ios

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?

like image 888
Wings Avatar asked Nov 05 '18 09:11

Wings


4 Answers

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

like image 125
fewlinesofcode Avatar answered Oct 22 '22 12:10

fewlinesofcode


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: " - ")
like image 44
CZ54 Avatar answered Oct 22 '22 14:10

CZ54


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"
    ]
))
like image 30
Callam Avatar answered Oct 22 '22 13:10

Callam


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) ?? ""
like image 1
Dávid Pásztor Avatar answered Oct 22 '22 14:10

Dávid Pásztor