SwiftPy is a fast and lightweight Python interpreter built on pocketpy with Swift macro binding tools.
dependencies: [
.package(url: "https://github.com/felfoldy/SwiftPy.git", from: "0.11.0")
]
Annotate your Swift classes with the @Scriptable
macro to automatically generate a corresponding Python interface. For example:
@Scriptable
@Observable
class LoginViewModel {
var username: String = ""
var password: String = ""
func login() {
...
}
}
This will generate an equivalent type for Python:
class LoginViewModel:
username: str
password: str
def login(self) -> None:
...
Inject the view model into Python using the interactable
modifier:
struct LoginView {
@State private var viewModel = LoginViewModel()
var body: some View {
viewImplementation
.interactable("viewmodel", viewModel)
}
}
After injection, Python scripts can interact with the Swift view model:
viewmodel = viewcontext.viewmodel
viewmodel.username = "username"
viewmodel.password = "password"
viewmodel.login()