Skip to content

Instantly share code, notes, and snippets.

@domingogallardo
Created May 17, 2022 09:31
Show Gist options
  • Save domingogallardo/957ba9d57cf3c2e0e2e432ceb0e06a13 to your computer and use it in GitHub Desktop.
Save domingogallardo/957ba9d57cf3c2e0e2e432ceb0e06a13 to your computer and use it in GitHub Desktop.
Ejemplo de lectura y escritura en ficheros de texto en Swift

Fichero write.swift:

import Foundation

let miStr = "1000.0 -43.1 4.523 \nHola cómo estás?\n"
let nombreFichero = "output.txt"

try? miStr.write(toFile: nombreFichero, atomically: true, encoding: .utf8)

Fichero read.swift:

import Foundation

let url = URL(fileURLWithPath: "./output.txt")

if let contenido = try? String(contentsOf: url, encoding: .utf8) {
    // Obtengo un array de cadenas separando los fines de línea
    let lineas = contenido.split(separator: "\n")

    // Obtengo los números
    let nums = lineas[0].split(separator: " ")
    let n1 = Double(nums[0])!
    let n2 = Double(nums[1])!
    let n3 = Double(nums[2])!

    print("Números leídos: \(n1) \(n2) \(n3)")
    print("Cadena leída: \(lineas[1])")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment