Swift framework to efficiently bridge objects from Python to Swift.
PythonCodable
requires Swift 5 or higher.
PythonCodable
builds on PythonKit
to allow bridging arbitrary Python objects into Swift types efficiently using PythonDecoder
:
import PythonKit
import PythonCodable
// 1. Get a valid Python object:
let urllibParse = Python.import("urllib.parse")
let pythonParsedURL = urllibParse.urlparse("http://www.cwi.nl:80/%7Eguido/Python.html")
print(pythonParsedURL) // ParseResult(scheme='http', netloc='www.cwi.nl:80'...
print(Python.type(pythonParsedURL)) // <class 'urllib.parse.ParseResult'>
// 2. Define a compatible Swift struct conforming to `Decodable`:
struct ParsedURL: Decodable {
let scheme: String
let netloc: String
let path: String
let params: String?
let query: String?
let fragment: String?
}
// 3. Decode the Python object as a Swift type using `PythonDecoder`:
let parsedURL = try PythonDecoder.decode(ParsedURL.self, from: pythonParsedURL)
XCTAssertEqual(parsedURL.scheme, "http")
XCTAssertEqual(parsedURL.netloc, "www.cwi.nl:80")
XCTAssertEqual(parsedURL.path, "/%7Eguido/Python.html")
PythonDecoder
supports multiple Python to Swift type conversions:
int
toInt
float
toDouble
bool
toBool
None
tonil
list[t]
toArray<T>
wheret
is one of the supported types.dict[k, v]
toDictionary<K, T>
wherek
is astr
andv
is one of the supported types.object
toAny : Decodable
whereobject
is adict
, a named tuple or an object with a dictionary representation.
Add the following dependency to your Package.swift
manifest:
.package(url: "https://github.com/pvieito/PythonCodable.git", .branch("master")),