简体   繁体   English

在 Swift 中处理大数组

[英]Handling large array in Swift

I have an array of English words that is about 275,000 elements long that I need to use for my iOS app written in Swift.我有一组大约 275,000 个元素的英文单词,我需要将它们用于我用 Swift 编写的 iOS 应用程序。 However, Xcode doesn't seem to be able to handle such a large (3+ MB) file.但是,Xcode 似乎无法处理这么大(3+ MB)的文件。 The file will not open in Xcode, and when I attempt to compile the app, it seems to compile indefinitely and never build.该文件不会在 Xcode 中打开,当我尝试编译该应用程序时,它似乎无限期地编译并且永远不会构建。

How should I handle this large amount of data?我该如何处理如此大量的数据?

Don't put a huge literal array in your swift source code.不要在你的 swift 源代码中放置一个巨大的文字数组。

Instead, create a text file, drag that into your project as a resource, then open that and convert it into an array at runtime using components(separatedBy:) .相反,创建一个文本文件,将其作为资源拖到您的项目中,然后打开它并在运行时使用components(separatedBy:)将其转换为数组。

For speed and storage efficiency you could instead write a conversion utility that reads your text file and uses components(separatedBy:) to convert it to an Array of Strings .为了速度和存储效率,您可以编写一个转换实用程序来读取您的文本文件并使用components(separatedBy:)将其转换为一个Array of Strings Then you could write the array of Strings to a binary plist.然后你可以将Strings数组写入二进制 plist。

You could then drag the plist file into your project as a resource, and write code that reads the plist file into an Array at launch.然后,您可以将 plist 文件作为资源拖到您的项目中,并编写代码在启动时将 plist 文件读入Array

How about put it in a file and read it at runtime?把它放在一个文件中并在运行时读取它怎么样? For example, put the elements in the a JSON array and store the array in a text file.例如,将元素放入 JSON 数组并将该数组存储在文本文件中。 Drag the file into your Xcode project, then it will be copied into the app bundle during compilation.将文件拖入您的 Xcode 项目,然后在编译期间将其复制到应用程序包中。 Read the JSON array from the file and parse it at runtime.从文件中读取 JSON 数组并在运行时解析它。

There are many Tutorial on the internet about reading files in bundle and parse JSON data.互联网上有很多关于读取包中的文件和解析 JSON 数据的教程。

Store it in a file Don't use array!, use Set (can sort before displaying). 将其存储在文件中不要使用array !,使用Set(可以在显示之前进行排序)。 If you have to use array consider https://www.hackingwithswift.com/example-code/language/how-to-split-an-array-into-chunks Use multithreading for processing. 如果必须使用数组,请考虑https://www.hackingwithswift.com/example-code/language/how-to-split-an-array-into-chunks使用多线程进行处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM