MacOS, iOS, TVOS 및 WatchOS에 대한 간단한 CSV 구문 분석.
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 입니다.
인식 된 목록에서 구분기를 추측하는 편의 초기화기를 사용할 수 있습니다. 이 초기화기는 URL 및 문자열에서 CSV를로드 할 수 있습니다.
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"] COLOUMN이 아닌 데이터 행으로 만 액세스하려면 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 전달하여 Column Access를 완전히 건너 뛰십시오. 이렇게하면 원주 데이터가 채워지는 것을 방지합니다. 큰 데이터 세트의 경우 많은 반복을 저장합니다 (2 차 런타임).
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")
패키지는 민감한 데이터에 액세스하거나 추적하지 않기 때문에 빈 프라이버시가 나타납니다.