Swift: System Access

Swift: System Access

Explain OS system access, file handling and parsing in Swift.

Here is an overview of OS system access, file handling and parsing in Swift:

OS System Access:

  • Swift provides easy access to the underlying operating system. You can access the file system, environment variables, launch processes, etc.

  • The Process class lets you launch new processes and interact with them.

  • The FileManager class provides methods to interact with the file system - copy, move, delete files and directories.

File Handling:

  • Swift makes it easy to read and write files.

  • You can use the readFile(atPath:) and writeFile(contents:atomically:encoding:error:) methods of FileManager to read from and write to files.

  • For text files, you can use String's initializer init(contentsOfFile:encoding:) and its write(toFile:atomically:encoding:) method.

  • For binary data, use Data's initializer init(contentsOf:) and its write(to:options:) method.


  • Swift has built-in support for parsing JSON, XML and plist files using the JSONSerialization, XMLParser and PropertyList classes.

  • You can also use 3rd party libraries like SwiftyJSON, AEXML, Plists to parse these file formats.

  • You can parse text files line by line using String's enumerateLines() method.

JSON Parser

Here is an example of parsing a JSON file in Swift:

JSON file example:

  "name": "John",
  "age": 30,
  "married": true, 
  "children": ["David","Mark"],
  "pets": null

Swift code:

import Foundation

if let url = Bundle.main.url(forResource: "data", withExtension: "json") {
    do {
        let data = try Data(contentsOf: url)
        let json = try JSONSerialization.jsonObject(with: data)

        if let dict = json as? [String: Any] {
            // Access properties
            if let name = dict["name"] as? String {
                print(name) // John
            if let age = dict["age"] as? Int {
                print(age) // 30

    } catch {

This code loads the JSON file from the main bundle, parses it using JSONSerialization and creates a dictionary that we can access the properties from.

Bash Command

Here is an example of running an external Bash command from Swift and using the result:

import Foundation

let task = Process()
task.launchPath = "/bin/bash"
task.arguments = ["-c", "echo Hello from Bash!"]

let pipe = Pipe()
task.standardOutput = pipe


let data = pipe.fileHandleForReading.readDataToEndOfFile()
let output = String(data: data, encoding: .utf8)!

// Prints "Hello from Bash!"

// We can now use the output in our Swift program
if output.contains("Bash") {
    print("The command was run in Bash")

This code does the following:

  1. Creates a Process to run an external command

  2. Sets the launchPath to /bin/bash

  3. Passes the echo command as an argument

  4. Creates a pipe to read the standard output

  5. Launches the process

  6. Reads the data from the pipe

  7. Converts it to a String

  8. Prints the output

  9. Checks if the output contains "Bash" and takes an action accordingly

The key is using the pipe to read the standard output of the external command and then using that output within our Swift program.

Disclaim: This short article is introducing you to power of Swift over the operating system. Is not complete quide how to use these features. For more examples subscribe to Sage-Code Laboratory. We will exmplain more.