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:
我有一个元组(String,String,String)数组,我想写入文本文件。我尝试过不同的方法,例如:
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'
无法将'[(String,String,String)]'类型的值转换为指定类型'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.
我已将我的项目上传到GitHub,供那些想要下载它的人使用。
1 个解决方案
#1
1
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:
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:
基本上,您现在已经创建了自己可以重用的类型(String,String,String)。如果您想将不同类型链接在一起,这非常方便。您应该能够将其保存为普通数组,而不会出现此错误:
Cannot convert value of type '[(String, String, String)]' to specified type 'NSArray'
#1
1
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:
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:
基本上,您现在已经创建了自己可以重用的类型(String,String,String)。如果您想将不同类型链接在一起,这非常方便。您应该能够将其保存为普通数组,而不会出现此错误:
Cannot convert value of type '[(String, String, String)]' to specified type 'NSArray'