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

  • A+
Category:Languages

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

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: