تحليل CSV بسيط لـ MacOS و iOS و TVOS و Watchos.
يمكن تحميل محتوى CSV باستخدام فئة CSV :
import SwiftCSV
do {
// As a string, guessing the delimiter
let csv : CSV = try CSV < Named > ( string : " id,name,age n 1,Alice,18 " )
// Specifying a custom delimiter
let tsv : CSV = try CSV < Enumerated > ( string : " id t name t age n 1 t Alice t 18 " , delimiter : . tab )
// From a file (propagating error during file loading)
let csvFile : CSV = try CSV < Named > ( url : URL ( fileURLWithPath : " path/to/users.csv " ) )
// From a file inside the app bundle, with a custom delimiter, errors, and custom encoding.
// Note the result is an optional.
let resource : CSV ? = try CSV < Named > (
name : " users " ,
extension : " tsv " ,
bundle : . main ,
delimiter : . character ( " ? " ) , // Any character works!
encoding : . utf8 )
} catch parseError as CSVParseError {
// Catch errors from parsing invalid CSV
} catch {
// Catch errors from trying to load files
} تأتي فئة CSV مع مبادئ أخرى مناسبة لتحميل الملفات من عناوين URL.
extension CSV {
/// Load a CSV file from `url`.
///
/// - Parameters:
/// - url: URL of the file (will be passed to `String(contentsOfURL:encoding:)` to load)
/// - delimiter: Character used to separate separate cells from one another in rows.
/// - encoding: Character encoding to read file (default is `.utf8`)
/// - loadColumns: Whether to populate the columns dictionary (default is `true`)
/// - Throws: `CSVParseError` when parsing the contents of `url` fails, or file loading errors.
public convenience init ( url : URL ,
delimiter : CSVDelimiter ,
encoding : String . Encoding = . utf8 ,
loadColumns : Bool = true ) throws
/// Load a CSV file from `url` and guess its delimiter from `CSV.recognizedDelimiters`, falling back to `.comma`.
///
/// - Parameters:
/// - url: URL of the file (will be passed to `String(contentsOfURL:encoding:)` to load)
/// - encoding: Character encoding to read file (default is `.utf8`)
/// - loadColumns: Whether to populate the columns dictionary (default is `true`)
/// - Throws: `CSVParseError` when parsing the contents of `url` fails, or file loading errors.
public convenience init ( url : URL ,
encoding : String . Encoding = . utf8 ,
loadColumns : Bool = true )
} يتم كتابة المحددات بقوة. حالات CSVDelimiter المعترف بها هي: .comma ، .semicolon ، و .tab .
يمكنك استخدام المهيمنات الراحة التي تخمن المحدد من القائمة المعترف بها لك. تتوفر هذه المهيئات لتحميل CSV من عناوين URL والسلاسل.
يمكنك أيضًا استخدام أي محدد أحادي الأحرف عند تحميل بيانات CSV. ستنتج شخصية حرفية مثل "x" CSV.Delimiter.character("x") ، لذلك لا يتعين عليك كتابة اسم الحالة .character(_) بالكامل. هناك أخصائيات لكل متغير يقبل إعدادات محدد صريحة.
// Recognized the comma delimiter automatically:
let csv = CSV < Named > ( string : " id,name,age n 1,Alice,18 n 2,Bob,19 " )
csv . header //=> ["id", "name", "age"]
csv . rows //=> [["id": "1", "name": "Alice", "age": "18"], ["id": "2", "name": "Bob", "age": "19"]]
csv . columns //=> ["id": ["1", "2"], "name": ["Alice", "Bob"], "age": ["18", "19"]]يمكن أيضًا تحليل الصفوف وتمريرها إلى كتلة على الطيران ، مما يقلل من الذاكرة اللازمة لتخزين المجموعة بأكملها في صفيف:
// Access each row as an array (inner array not guaranteed to always be equal length to the header)
csv . enumerateAsArray { array in
print ( array . first )
}
// Access them as a dictionary
csv . enumerateAsDict { dict in
print ( dict [ " name " ] )
} استخدم CSV<Named> AKA NamedCSV للوصول إلى بيانات CSV على أساس عمود على حدة مع أعمدة مسماة. فكر في هذا مثل المقطع العرضي:
let csv = NamedCSV ( string : " id,name,age n 1,Alice,18 n 2,Bob,19 " )
csv . rows [ 0 ] [ " name " ] //=> "Alice"
csv . columns [ " name " ] //=> ["Alice", "Bob"] إذا كنت ترغب فقط في الوصول إلى بيانات صفك على حدة ، وليس من قبل العمود ، فيمكنك استخدام CSV<Enumerated> أو EnumeratedCSV :
let csv = EnumeratedCSV ( string : " id,name,age n 1,Alice,18 n 2,Bob,19 " )
csv . rows [ 0 ] [ 1 ] //=> "Alice"
csv . columns ? [ 0 ] . header //=> "name"
csv . columns ? [ 0 ] . rows //=> ["Alice", "Bob"] لتسريع الأمور ، تخطي الوصول إلى العمود بالكامل عن طريق تمرير loadColumns: false . هذا سوف يمنع البيانات العمودية من ملء. بالنسبة لمجموعات البيانات الكبيرة ، يوفر هذا الكثير من التكرارات (في وقت التشغيل التربيعي).
let csv = EnumeratedCSV ( string : " id,name,age n 1,Alice,18 n 2,Bob,19 " , loadColumns : false )
csv . rows [ 0 ] [ 1 ] //=> "Alice"
csv . columns //=> nil pod "SwiftCSV" github "swiftcsv/SwiftCSV"
.package(url: "https://github.com/swiftcsv/SwiftCSV.git", from: "0.8.0")
تشحن الحزمة مع بيان خصوصية فارغ لأنه لا يصل أو تتبع أي بيانات حساسة.