Runtime is a Swift library to give you more runtime abilities, including getting type metadata, setting properties via reflection, and type construction for native swift objects.
TypeInfo
exposes metadata about native Swift structs, protocols, classes, tuples and enums. It captures the properties, generic types, inheritance levels, and more.
Lets say you have a User struct:
struct User {
let id: Int
let username: String
let email: String
}
To get the TypeInfo
of User
, all that you have to do is:
let info = try typeInfo(of: User.self)
Within the TypeInfo
object, it contains a list of PropertyInfo
which represents all properties for the type. PropertyInfo
exposes the name and type of the property. It also allows the getting and setting of a value on an object.
Using the same User
object as before first we get the TypeInfo
and the property we want.
let info = try typeInfo(of: User.self)
let property = try info.property(named: "username")
To get a value:
let username = try property.get(from: user)
To set a value:
try property.set(value: "newUsername", on: &user)
It's that easy! 🎉
Runtime also supports building an object from it's Type
. Both structs and classes are supported.
To build a User
object:
let user = try createInstance(type: User.self)
FunctionInfo
exposes metadata about functions. Including number of arguments, argument types, return types, and whether it can throw an error.
func doSomething(a: Int, b: Bool) throws -> String {
return ""
}
let info = functionInfo(of: doSomething)
Q: When getting and setting a value does it work typeless? (i.e. object casted as Any
)
A: Yes! The whole library was designed with working typeless in mind.
Q: When creating a new instance of a class is it still protected by ARC?
A: Yes! The retain counts are set properly so ARC can do its job.
Runtime is available through CocoaPods. To install it, simply add the following line to your Podfile:
pod 'Runtime'
You can install Runtime via Swift Package Manager by adding the following line to your Package.swift
:
import PackageDescription
let package = Package(
[...]
dependencies: [
.Package(url: "https://github.com/wickwirew/Runtime.git", majorVersion: XYZ)
]
)
Contributions are welcome and encouraged!
Want to know how it works? Here's an article on how it was implemented.
Want to learn about Swift memory layout? Mike Ash gave and awesome talk on just that.
Runtime is available under the MIT license. See the LICENSE file for more info.