1

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.

5
  • 1
    Does your tuple have to be a tuple? What if you created a struct that has 3 string values? Commented May 31, 2016 at 19:06
  • @NSGangster I'm rather new to Swift so excuse the noob question: for structs, can I have multiple values for each string? My current array is as follows: listOfTasks : [(String,String,String)] = [] And I fill that up with multiple tuples. Commented May 31, 2016 at 19:10
  • Just make an array of arrays. [[String, String, String]] Tuples are for when you have different types you want to link together. Commented May 31, 2016 at 19:32
  • 99% people ask about tuples: they should be using structs Commented May 31, 2016 at 19:34
  • @rMickeyD How do I access the individual strings? I was using .0, .1, etc. EDIT: NVM, I used listOfTasks[0][0] for example. Commented May 31, 2016 at 19:39

1 Answer 1

2

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'
Sign up to request clarification or add additional context in comments.

1 Comment

I did not answer the saving to file because it is a very general question that you can figure out if you google it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.