Alek Szczęsnowicz
Alek Szczęsnowicz

Reputation: 93

string to tuple swift

I'm trying to import data from a text file. I can read the file, but I don't know how to parse the String to something else, e.g. tuple.

The data in the file (text.txt) is formatted as pixels and their colors

(((0, 0), (1, 0), (2, 0), (3, 0), (4, 0), (5, 0)),((63479, 62451, 63479), (63479, 62451, 63479), (63479, 62451, 63479), (63479, 62451, 63479), (63479, 62451, 63479))

Here's my code so far:

//
//  ViewController.swift

import Cocoa

class ViewController: NSViewController {

    @IBAction func passPix(_ sender: Any) {
        let fileURL = "/Users/IMac/Desktop/text.txt"
        var inString = ("Pix+Col")
        do {
            inString = try String(contentsOfFile: fileURL, encoding:String.Encoding.utf8)

        } catch let error as NSError {
            print("Failed reading from URL: \(fileURL), Error: " + error.localizedDescription)
        }

        print(inString)
    }

}

Upvotes: 1

Views: 1187

Answers (1)

Bogdan Farca
Bogdan Farca

Reputation: 4106

Here's my take on it. Basically you replace the round brackets with square brackets in your original String, convert it to a JSON object and then traverse the resulting JSON object as you see fit :

let s = "(((0, 0), (1, 0), (2, 0), (3, 0), (4, 0)),((63479, 62451, 63479), (63479, 62451, 63479), (63479, 62451, 63479), (63479, 62451, 63479), (63479, 62451, 63479)))"

var js = String(s.characters.map { $0 == "(" ? "[" : $0 })
js = String(js.characters.map { $0 == ")" ? "]" : $0 })

var data = js.data(using: .utf8)
let json = try! JSONSerialization.jsonObject(with: data!) as! [Any]

let coords = json[0] as! [Any]
let rgbs = json[1] as! [Any]

for (i, coord) in coords.enumerated() {
    print ("\(coord) - \(rgbs[i])")
}

The output will be something like this:

[0, 0] - [63479, 62451, 63479]
[1, 0] - [63479, 62451, 63479]
[2, 0] - [63479, 62451, 63479]
[3, 0] - [63479, 62451, 63479]
[4, 0] - [63479, 62451, 63479]

So, at each iteration you get one array with the x,y coordinates and another one with the r,g,b color values of the pixel. You could easily convert them to tuples but I see little need to do so at this point.

Upvotes: 1

Related Questions