ghostpotato ghostpotato - 6 months ago 23
Swift Question

Write array of tuples to text file

I have an array of tuples (

String, String, String
) that I want to write to a text file. I've tried different methods such as:

let mySwiftArray = ... // Your Swift array
let cocoaArray : NSArray = mySwiftArray
cocoaArray.writeToFile(filePath, atomically:true)


But this gives me an error:

Cannot convert value of type '[(String, String, String)]' to specified type 'NSArray'


What can I do to write my array to a file?

I've uploaded my project to GitHub for those who would like to download it.

Answer

The issue is that even though tuple is technically a type it can always be different. In order to prevent it from being different you need to create a typealias:

typealias myStringTuple = (String, String, String)

var myArray = [myStringTuple]()

myArray.append(("Hello", "Goodbye", "See you later"))

print(myArray[0].1) // prints Goodbye

Basically, you have now created your own type of (String, String, String) that you can reuse. This comes in very handy if you want to link together different types. You should be able to save it as a normal array now without getting this error:

Cannot convert value of type '[(String, String, String)]' to specified type 'NSArray'