i want to add only the values of 2 dictionaries - ios

I have a swift code which is auto migrated from objective C to swift where is am getting an error
"Binary operator '+' cannot be applied to two 'Dictionary.Values' operands".
Because i trying to add the values of a dictionary which is not allowed. but how to add the values others wise. Below is the code where i am getting this error.
var result = cellAttrDict.values + supplHeaderAttrDict.values
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
var i: Int
var begin = 0
var end = unionRects.count
var cellAttrDict: [AnyHashable : Any] = [:]
var supplHeaderAttrDict: [AnyHashable : Any] = [:]
var supplFooterAttrDict: [AnyHashable : Any] = [:]
var decorAttrDict: [AnyHashable : Any] = [:]
for i in 0..<unionRects.count {
if rect.intersects(unionRects[i] as! CGRect) {
begin = i * unionSize
break
}
}
i = unionRects.count - 1
while i >= 0 {
if rect.intersects(unionRects[i] as! CGRect) {
end = min((i + 1) * unionSize, allItemAttributes.count)
break
}
i -= 1
}
for i in begin..<end {
let attr = allItemAttributes[i] as? UICollectionViewLayoutAttributes
if rect.intersects(attr?.frame ?? 0 as! CGRect) {
switch attr?.representedElementCategory {
case .supplementaryView?:
if (attr?.representedElementKind == CHTCollectionElementKindSectionHeader) {
if let indexPath = attr?.indexPath, let attr = attr {
supplHeaderAttrDict[indexPath] = attr
}
} else if (attr?.representedElementKind == CHTCollectionElementKindSectionFooter) {
if let indexPath = attr?.indexPath, let attr = attr {
supplFooterAttrDict[indexPath] = attr
}
}
case .decorationView?:
if let indexPath = attr?.indexPath, let attr = attr {
decorAttrDict[indexPath] = attr
}
case .cell?:
if let indexPath = attr?.indexPath, let attr = attr {
cellAttrDict[indexPath] = attr
}
#unknown default:
break
}
}
}
var result = cellAttrDict.values + supplHeaderAttrDict.values
result = result + supplFooterAttrDict.values
result = result + decorAttrDict.values
return result as? [UICollectionViewLayoutAttributes]
}

Dictionary.Values is a special lightweight view to the dictionary values to avoid allocating extra memory.
To be able to concatenate multiple values you have to create regular arrays
var result = Array(cellAttrDict.values) + Array(supplHeaderAttrDict.values)
result += Array(supplFooterAttrDict.values)
result += Array(decorAttrDict.values)
return result as? [UICollectionViewLayoutAttributes]

Related

How can I guarantee that a Swift closure (referencing Firebase) fully executes before I move on?

I have multiple query snapshots with closures and some of them are using the data supplied by the query that came before it.
I have read up on GCD and I've tried to implement a DispatchGroup with .enter() and .leave() but I am apparently doing something wrong.
If somebody can help me by laying out exactly how to force one task to be performed before another, that would solve my problem.
If you can't tell, I am somewhat new to this so any help is greatly appreciated.
//MARK: Get all userActivities with distance(All Code)
static func getAllChallengesWithDistanceAllCode(activity:String, completion: #escaping ([Challenge]) -> Void) {
let db = Firestore.firestore()
let currUserID = Auth.auth().currentUser!.uid
var currUserName:String?
var distanceSetting:Int?
var senderAverage:Double?
var senderBestScore:Int?
var senderMatchesPlayed:Double?
var senderMatchesWon:Double?
var senderWinPercentage:Double?
var validUserActivities = [Challenge]()
db.collection("users").document(currUserID).getDocument { (snapshot, error) in
if error != nil || snapshot == nil {
return
}
currUserName = snapshot?.data()!["userName"] as? String
distanceSetting = snapshot?.data()!["distanceSetting"] as? Int
}
db.collection("userActivities").document(String(currUserID + activity)).getDocument { (snapshot, error) in
//check for error
//MARK: changed snapshot to shapshot!.data() below (possible debug tip)
if error != nil {
//is error or no data..??
return
}
if snapshot!.data() == nil {
return
}
//get profile from data proprty of snapshot
if let uActivity = snapshot!.data() {
senderBestScore = uActivity["bestScore"] as? Int
senderMatchesPlayed = uActivity["played"] as? Double
senderMatchesWon = uActivity["wins"] as? Double
senderAverage = uActivity["averageScore"] as? Double
senderWinPercentage = round((senderMatchesWon! / senderMatchesPlayed!) * 1000) / 10
}
}
if distanceSetting != nil {
db.collection("userActivities").whereField("activity", isEqualTo: activity).getDocuments { (snapshot, error) in
if error != nil {
print("something went wrong... \(String(describing: error?.localizedDescription))")
return
}
if snapshot == nil || snapshot?.documents.count == 0 {
print("something went wrong... \(String(describing: error?.localizedDescription))")
return
}
if snapshot != nil && error == nil {
let uActivitiesData = snapshot!.documents
for uActivity in uActivitiesData {
let userID = uActivity["userID"] as! String
UserService.determineDistance(otherUserID: userID) { (determinedDistance) in
if determinedDistance! <= distanceSetting! && userID != currUserID {
var x = Challenge()
//Sender
x.senderUserID = currUserID
x.senderUserName = currUserName
x.senderAverage = senderAverage
x.senderBestScore = senderBestScore
x.senderMatchesPlayed = senderMatchesPlayed
x.senderMatchesWon = senderMatchesWon
x.senderWinPercentage = senderWinPercentage
//Receiver
x.receiverUserID = userID
x.receiverUserName = uActivity["userName"] as? String
x.receiverAverage = uActivity["averageScore"] as? Double
x.receiverBestScore = uActivity["bestScore"] as? Int
if (uActivity["played"] as! Double) < 1 || (uActivity["played"] as? Double) == nil {
x.receiverMatchesPlayed = 0
x.receiverMatchesWon = 0
x.receiverWinPercentage = 0
} else {
x.receiverMatchesPlayed = uActivity["played"] as? Double
x.receiverMatchesWon = uActivity["wins"] as? Double
x.receiverWinPercentage = ((uActivity["wins"] as! Double) / (uActivity["played"] as! Double) * 1000).rounded() / 10
}
if uActivity["playStyle"] as? String == nil {
x.receiverPlayStyle = "~No PlayStyle~"
} else {
x.receiverPlayStyle = uActivity["playStyle"] as! String
}
x.activity = activity
//append to array
validUserActivities.append(x)
}
}
}
completion(validUserActivities)
}
}
}
}
try this
static func getAllChallengesWithDistanceAllCode(activity:String, completion: #escaping ([Challenge]) -> Void) {
let db = Firestore.firestore()
let currUserID = Auth.auth().currentUser!.uid
var currUserName:String?
var distanceSetting:Int?
var senderAverage:Double?
var senderBestScore:Int?
var senderMatchesPlayed:Double?
var senderMatchesWon:Double?
var senderWinPercentage:Double?
var validUserActivities = [Challenge]()
db.collection("users").document(currUserID).getDocument { (snapshot, error) in
if error != nil || snapshot == nil {
return
}
currUserName = snapshot?.data()!["userName"] as? String
distanceSetting = snapshot?.data()!["distanceSetting"] as? Int
db.collection("userActivities").document(String(currUserID + activity)).getDocument { (snapshot, error) in
//check for error
//MARK: changed snapshot to shapshot!.data() below (possible debug tip)
if error != nil {
//is error or no data..??
return
}
if snapshot!.data() == nil {
return
}
//get profile from data proprty of snapshot
if let uActivity = snapshot!.data() {
senderBestScore = uActivity["bestScore"] as? Int
senderMatchesPlayed = uActivity["played"] as? Double
senderMatchesWon = uActivity["wins"] as? Double
senderAverage = uActivity["averageScore"] as? Double
senderWinPercentage = round((senderMatchesWon! / senderMatchesPlayed!) * 1000) / 10
if snapshot != nil && error == nil {
let uActivitiesData = snapshot!.documents
for uActivity in uActivitiesData {
let userID = uActivity["userID"] as! String
UserService.determineDistance(otherUserID: userID) { (determinedDistance) in
if determinedDistance! <= distanceSetting! && userID != currUserID {
var x = Challenge()
//Sender
x.senderUserID = currUserID
x.senderUserName = currUserName
x.senderAverage = senderAverage
x.senderBestScore = senderBestScore
x.senderMatchesPlayed = senderMatchesPlayed
x.senderMatchesWon = senderMatchesWon
x.senderWinPercentage = senderWinPercentage
//Receiver
x.receiverUserID = userID
x.receiverUserName = uActivity["userName"] as? String
x.receiverAverage = uActivity["averageScore"] as? Double
x.receiverBestScore = uActivity["bestScore"] as? Int
if (uActivity["played"] as! Double) < 1 || (uActivity["played"] as? Double) == nil {
x.receiverMatchesPlayed = 0
x.receiverMatchesWon = 0
x.receiverWinPercentage = 0
} else {
x.receiverMatchesPlayed = uActivity["played"] as? Double
x.receiverMatchesWon = uActivity["wins"] as? Double
x.receiverWinPercentage = ((uActivity["wins"] as! Double) / (uActivity["played"] as! Double) * 1000).rounded() / 10
}
if uActivity["playStyle"] as? String == nil {
x.receiverPlayStyle = "~No PlayStyle~"
} else {
x.receiverPlayStyle = uActivity["playStyle"] as! String
}
x.activity = activity
//append to array
validUserActivities.append(x)
}
}
}
completion(validUserActivities)
}
}
}
}
}
}
}
I solved this by doing the following:
Add a constant before the for-in loop counting the total number of query results
let documentCount = snapshot?.documents.count
Add a counter before the for-in loop starting at 0
var runCounter = 0
Increment the counter with each iteration at the beginning of the for-in loop
runCounter += 1
Add code to the end of the for-in loop to call the completion handler to return the results
if runCounter == documentCount {
completion(validChallenges)
}

class_copyPropertyList not working in Swift 5. Whats the reason?

class_copyPropertyList is giving empty properties in Swift 5 and it was working correct in Swift 3
extension NSObject {
func toDictionary(from classType: NSObject.Type) -> [String: Any] {
var propertiesCount : CUnsignedInt = 0
let propertiesInAClass = class_copyPropertyList(classType, &propertiesCount)
let propertiesDictionary : NSMutableDictionary = NSMutableDictionary()
for i in 0 ..< Int(propertiesCount) {
let property = propertiesInAClass?[i]
let strKey = NSString(utf8String: property_getName(property)) as String?
if let key = strKey {
propertiesDictionary.setValue(self.value(forKey: key), forKey: key)
}
}
return propertiesDictionary as! [String : Any]
}
}
// call this for NSObject subclass
let product = Product()
let dict = product.toDictionary(from: Product.self)
print(dict)

Force casts should be avoided

I am getting "Force cast violation : Force casts should be avoided warning"
on my code :
daysCombinedFinal = daysCombined[0] as! [Any?]
The screenshot is attached below:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: "location", for: indexPath) as? TravelShopCustomCell {
if !isFirstTime && self.nameArray.count != 0 {
var daysCombined = [Any]()
var daysCombinedFinal = [Any?]()
daysCombined = [self.combinedArray[0]]
daysCombinedFinal = daysCombined[0] as? [Any?] ?? []
let str = daysCombinedFinal.flatMap { $0 as? String }.joined(separator:" ")
var startAMCombined = [Any]()
var startAMCombinedFinal = [Any?]()
startAMCombined = [self.combinedStartAMArray[0]]
startAMCombinedFinal = startAMCombined[0] as? [Any?] ?? []
var endPMCombined = [Any]()
var endPMCombinedFinal = [Any?]()
endPMCombined = [self.combinedEndPMArray[0]]
endPMCombinedFinal = endPMCombined[0] as? [Any?] ?? []
cell.operatingDaysLabel.text = str
let isAMEqual = checkArrayStatus(testArray: [startAMCombinedFinal as Any])
let isPMEqual = checkArrayStatus(testArray: [endPMCombinedFinal as Any])
if isAMEqual && isPMEqual {
self.mergedArray = arrayMerger(array1: startAMCombinedFinal, array2: endPMCombinedFinal)
}
let startTimeString = self.mergedArray[0] as? String
let endTimeString = self.mergedArray[1] as? String
cell.operatingTimeLabel.text = startTimeString! + " - " + endTimeString!
return cell
} else if isFirstTime && self.nameArray.count != 0 {
var daysCombined = [Any]()
var daysCombinedFinal = [Any?]()
daysCombined = [self.combinedArray[indexPath.row]]
daysCombinedFinal = daysCombined[0] as! [Any?]
let str = daysCombinedFinal.flatMap { $0 as? String }.joined(separator:" ")
var startAMCombined = [Any]()
var startAMCombinedFinal = [Any?]()
startAMCombined = [self.combinedStartAMArray[indexPath.row]]
startAMCombinedFinal = startAMCombined[0] as! [Any?]
var endPMCombined = [Any]()
var endPMCombinedFinal = [Any?]()
endPMCombined = [self.combinedEndPMArray[indexPath.row]]
endPMCombinedFinal = endPMCombined[0] as! [Any?]
cell.operatingDaysLabel.text = str
let isAMEqual = checkArrayStatus(testArray: [startAMCombinedFinal as Any])
let isPMEqual = checkArrayStatus(testArray: [endPMCombinedFinal as Any])
if isAMEqual && isPMEqual {
self.mergedArray = arrayMerger(array1: startAMCombinedFinal, array2: endPMCombinedFinal)
}
let startTimeString = self.mergedArray[0] as? String
let endTimeString = self.mergedArray[1] as? String
cell.operatingTimeLabel.text = startTimeString! + " - " + endTimeString!
return cell
}
return cell
} else {
fatalError("Dequeueing SomeCell failed")
}
}
The array declaration is:
var dateArray = [Any]()
var endAmTimeArray = [Any]()
var endPmTimeArray = [Any]()
var startAmTimeArray = [Any]()
var startPmTimeArray = [Any]()
var combinedArray = [Any]()
var combinedStartAMArray = [Any]()
var combinedEndPMArray = [Any]()
var mergedArray = [Any?]()
Your problem has relation with concept of 'optional' & 'unwrapper'. Here is brief about both and difference between them: How to understand ! and ? in swift?
? (Optional) indicates your variable may contain a nil value while ! (unwrapper) indicates your variable must have a memory (or value) when it is used (tried to get a value from it) at runtime.
In your case, you are trying to get value from array using index number. Now type of elements of your array is 'Any'
So, there may be any kind of value/information contained by element of array. It will result into app crash, if you try to force unwrap a value of element, when it won't return a value or value with type that you're casting with unwrapper.
Here is basic tutorial in detail, by Apple Developer Committee.
This warning is indicating you, that your app may crash on force unwrapping optional value.
As a solution you should use ? (optional) with if-let block, to avoid force unwrapping and safe execution of your code, like:
if let daysC = daysCombined[0] as? [Any] {
daysCombinedFinal = daysC
}
Share your full source code, to get better solution of your query as you have not shared declaration of your array in your question. Because I've confusion about optional array [Any?] elements. Swift not allows array elements as optional.
Update : By considering elements of all arrays as 'Dictionary < String : Any >', forced unwraps from array assignments are removed here.
var daysCombined = [Any]()
var daysCombinedFinal = [Any?]()
daysCombined = [self.combinedArray[indexPath.row]]
// Update 1
// if combinedArray is an array of array
if let arrayElement = daysCombined[0] as? [Any] {
daysCombinedFinal = arrayElement
}
let str = daysCombinedFinal.flatMap { $0 as? String }.joined(separator:" ")
var startAMCombined = [Any]()
var startAMCombinedFinal = [Any?]()
startAMCombined = [self.combinedStartAMArray[indexPath.row]]
// Update 2
if let arrayElement = startAMCombined[0] as? [Any] {
startAMCombinedFinal = arrayElement
}
var endPMCombined = [Any]()
var endPMCombinedFinal = [Any?]()
endPMCombined = [self.combinedEndPMArray[indexPath.row]]
// Update 3
if let arrayElement = endPMCombined[0] as? [Any] {
endPMCombinedFinal = arrayElement
}
cell.operatingDaysLabel.text = str

Why can I not access the second level of this array in Swift?

I have the following array which is passed from an API call from a PHP Script:
["playerForm": {
1 = (
{
date = "2017-01-31";
name = Dicky;
result = L;
"results_id" = 42;
},
{
date = "2016-12-24";
name = Dicky;
result = W;
"results_id" = 19;
}
);
2 = (
{
date = "2017-01-25";
name = G;
result = W;
"results_id" = 38;
},
{
date = "2017-01-25";
name = G;
result = D;
"results_id" = 40;
},
{
date = "2017-01-21";
name = G;
result = L;
"results_id" = 34;
}
);
3 = (
{
date = "2017-01-31";
name = Sultan;
result = W;
"results_id" = 42;
},
{
date = "2017-01-15";
name = Sultan;
result = L;
"results_id" = 30;
}
);
}]
However I cannot seem to access the 1,2,3 parts of it...
let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String:AnyObject]
print (json!)
if let dict = json?["playerForm"] as? [String:AnyObject] {
print ("step 1")
if let arr = dict["1"] as? [[String:String]] {
print ("step 2")
self.leagueForm = arr.flatMap { Form($0) }
print (self.leagueForm)
print (self.leagueForm.count)
for i in 0..<self.leagueForm.count {
let form = self.leagueForm[i]
print (form.player_results!)
self.formGuide.append(form.player_results!)
}
print ("now")
print (self.formGuide)
self.resultsDisplay.results = self.formGuide
self.resultsDisplay.results = self.resultsDisplay.results.reversed()
self.resultsDisplay.displayResults()
}
}
With this code above it only gets as far as Step 1.
What am I doing wrong?
UPDATED WITH PROGRSS*
let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String:AnyObject]
print (json!)
if let dict = json?["playerForm"] as? [String:AnyObject] {
print ("step 1")
for (_ , value) in dict {
if let arr = value as? [[String:Any]] {
print(arr)
//your code
}
}
}
Custom Struct to define array:
struct Form {
var player_result: String?
var player_name: String?
var result_date: String?
var result_id: String?
init(_ dictionary: [String : Any]) {
self.player_result = dictionary["result"] as? String ?? ""
self.player_name = dictionary["name"] as? String ?? ""
result_date = dictionary["date"] as? String ?? ""
result_id = String(dictionary["results_id"] as? Int ?? 0)
}
}
Change your array type [[String:String]] to [[String:Any]] because it contains both String and Number as value.
if let arr = dict["1"] as? [[String:Any]] {
print(arr)
//your code
}
Note: You need to loop through the dict Dictionary because its each key having array.
for (_ , value) in dict {
if let arr = value as? [[String:Any]] {
print(arr)
//your code
}
}

Splitting a string in swift using multiple delimiters

I am trying to split (or explode) a string in Swift (1.2) using multiple delimiters, or seperators as Apple calls them.
My string looks like this:
KEY1=subKey1=value&subkey2=valueKEY2=subkey1=value&subkey2=valueKEY3=subKey1=value&subkey3=value
I have formatted it for easy reading:
KEY1=subKey1=value&subkey2=value
KEY2=subkey1=value&subkey2=value
KEY3=subKey1=value&subkey3=value
The uppercase "KEY" are predefined names.
I was trying to do this using:
var splittedString = string.componentsSeparatedByString("KEY1")
But as you can see, I can only do this with one KEY as the separator, so I am looking for something like this:
var splittedString = string.componentsSeperatedByStrings(["KEY1", "KEY2", "KEY3"])
So the result would be:
[
"KEY1" => "subKey1=value&subkey2=value",
"KEY2" => "subkey1=value&subkey2=value",
"KEY3" => "subkey1=value&subkey2=value"
]
Is there anything built into Swift 1.2 that I can use?
Or is there some kind of extension/library that can do this easily?
Thanks for your time, and have a great day!
One can also use the following approach to split a string with multiple delimiters in case keys are single characters:
//swift 4+
let stringData = "K01L02M03"
let res = stringData.components(separatedBy: CharacterSet(charactersIn: "KLM"))
//older swift syntax
let res = stringData.componentsSeparatedByCharactersInSet(NSCharacterSet(charactersInString: "KLM"));
res will contain ["01", "02", "03"]
If anyone knows any kind of special syntax to extend the approach to multiple characters per key you are welcome to suggest and to improve this answer
Swift 4.2 update to #vir us's answer:
let string = "dots.and-hyphens"
let array = string.components(separatedBy: CharacterSet(charactersIn: ".-"))
This isn't very efficient, but it should do the job:
import Foundation
extension String {
func componentsSeperatedByStrings(ss: [String]) -> [String] {
let inds = ss.flatMap { s in
self.rangeOfString(s).map { r in [r.startIndex, r.endIndex] } ?? []
}
let ended = [startIndex] + inds + [endIndex]
let chunks = stride(from: 0, to: ended.count, by: 2)
let bounds = map(chunks) { i in (ended[i], ended[i+1]) }
return bounds
.map { (s, e) in self[s..<e] }
.filter { sl in !sl.isEmpty }
}
}
"KEY1=subKey1=value&subkey2=valueKEY2=subkey1=value&subkey2=valueKEY3=subKey1=value&subkey3=value".componentsSeperatedByStrings(["KEY1", "KEY2", "KEY3"])
// ["=subKey1=value&subkey2=value", "=subkey1=value&subkey2=value", "=subKey1=value&subkey3=value"]
Or, if you wanted it in dictionary form:
import Foundation
extension String {
func componentsSeperatedByStrings(ss: [String]) -> [String:String] {
let maybeRanges = ss.map { s in self.rangeOfString(s) }
let inds = maybeRanges.flatMap { $0.map { r in [r.startIndex, r.endIndex] } ?? [] }
let ended = [startIndex] + inds + [endIndex]
let chunks = stride(from: 0, to: ended.count, by: 2)
let bounds = map(chunks) { i in (ended[i], ended[i+1]) }
let values = bounds
.map { (s, e) in self[s..<e] }
.filter { sl in !sl.isEmpty }
let keys = filter(zip(maybeRanges, ss)) { (r, _) in r != nil }
var result: [String:String] = [:]
for ((_, k), v) in zip(keys, values) { result[k] = v }
return result
}
}
"KEY1=subKey1=value&subkey2=valueKEY2=subkey1=value&subkey2=valueKEY3=subKey1=value&subkey3=value".componentsSeperatedByStrings(["KEY1", "KEY2", "KEY3"])
// ["KEY3": "=subKey1=value&subkey3=value", "KEY2": "=subkey1=value&subkey2=value", "KEY1": "=subKey1=value&subkey2=value"]
For Swift 2:
import Foundation
extension String {
func componentsSeperatedByStrings(ss: [String]) -> [String] {
let unshifted = ss
.flatMap { s in rangeOfString(s) }
.flatMap { r in [r.startIndex, r.endIndex] }
let inds = [startIndex] + unshifted + [endIndex]
return inds.startIndex
.stride(to: inds.endIndex, by: 2)
.map { i in (inds[i], inds[i+1]) }
.flatMap { (s, e) in s == e ? nil : self[s..<e] }
}
}
Swift 5:
extension String {
func components<T>(separatedBy separators: [T]) -> [String] where T : StringProtocol {
var result = [self]
for separator in separators {
result = result
.map { $0.components(separatedBy: separator)}
.flatMap { $0 }
}
return result
}
}
It's for the sack of nice and neat code, don't use it if you need something efficiently
Swift 2 for forward compatibility
Using a regular expression:
let string = "KEY1=subKey1=value&subkey2=valueKEY2=subkey1=value&subkey2=valueKEY3=subKey1=value&subkey3=value"
let nsString :NSString = string
let stringRange = NSMakeRange(0, string.utf16.count)
let pattern = "(KEY\\d)=([^=]+=[^&]+[^=]+?=[^K]+)"
var results = [String:String]()
do {
var regEx = try NSRegularExpression(pattern:pattern, options:[])
regEx.enumerateMatchesInString(string, options: [], range: stringRange) {
(result : NSTextCheckingResult?, _, _) in
if let result = result {
if result.numberOfRanges == 3 {
let key = nsString.substringWithRange(result.rangeAtIndex(1))
let value = nsString.substringWithRange(result.rangeAtIndex(2))
results[key] = value
}
}
}
}
catch {
print("Bad Pattern")
}
results: ["KEY3": "subKey1=value&subkey3=value", "KEY2": "subkey1=value&subkey2=value", "KEY1": "subKey1=value&subkey2=value"]
You could do it with regular expressions. The below snippet is a bit clumsy and not really fail-safe but it should give you an idea.
let string = "KEY1=subKey1=value&subkey2=valueKEY2=subkey1=value&subkey2=valueKEY3=subKey1=value&subkey3=value"
let re = NSRegularExpression(pattern: "(KEY1|KEY2|KEY3)=", options: nil, error: nil)!
let matches = re.matchesInString(string, options: nil,
range: NSMakeRange(0, count(string)))
var dict = [String: String]()
for (index, match) in enumerate(matches) {
let key = (string as NSString).substringWithRange(
NSMakeRange(match.range.location, match.range.length - 1))
let valueStart = match.range.location + match.range.length
let valueEnd = index < matches.count - 1 ? matches[index + 1].range.location
: count(string)
let value = (string as NSString).substringWithRange(
NSMakeRange(valueStart, valueEnd - valueStart))
dict[key] = value
}
The final value of dict is
[KEY3: subKey1=value&subkey3=value,
KEY2: subkey1=value&subkey2=value,
KEY1: subKey1=value&subkey2=value]

Resources