Skip to main content

Variants (A | B | ...)

A Variant is a type of either one of the values defined in its declaration. Example:

import { type HybridObject, iOS } from 'nitro-core'

@iOS(...)
export declare class Math extends HybridObject {
distance(value: number | Point): number
}
tip

While variants are still very efficient, they need runtime-checks for type conversions, which comes with a tiny overhead compared to all other statically defined types. If possible, avoid variants.

No literal values​

A variant can only consist of types, not of literal values.

import { type HybridObject, iOS } from 'nitro-core'

@iOS(...)
export declare class Person extends HybridObject {
getGender(): 'male' | 'female'
}

If you need variants of literal values, you probably want to use an enum (union) instead.

Custom Alias Names​

Each variant is a unique type in Swift/Kotlin - for example: string | number becomes Variant_String_Double.

Since the generated names are hard to read, it is recommended to declare type-aliases with custom names instead:

Bad ❌
import { type HybridObject, iOS } from 'nitro-core'


@iOS(...)
export declare class Math extends HybridObject {
calculate(): string | number
}
Good ✅
import { type HybridObject, iOS } from 'nitro-core'

type MathOutput = string | number
@iOS(...)
export declare class Math extends HybridObject {
calculate(): MathOutput
}

This will then use the easier-to-read type-alias name instead of Variant_String_Double:

HybridMath.swift
class HybridMath: HybridMathSpec {
func calculate() throws -> Variant_String_Double
func calculate() throws -> MathOutput
}