### Kotlin Data Class Example Source: https://github.com/kotlin-hands-on/kotlin-swift-interopedia/blob/main/docs/classesandinterfaces/Data classes.md Demonstrates a typical data class definition in Kotlin with various parameter types. ```kotlin data class DataClass( val param1: String, val param2: Int, val param3: Boolean ) ``` -------------------------------- ### Kotlin Sealed Interfaces to Swift Source: https://github.com/kotlin-hands-on/kotlin-swift-interopedia/blob/main/README.md Describes the handling of Kotlin sealed interfaces in Swift. Separate, unrelated protocols are generated for each heir. ```Swift // Separate protocols are generated that are not related to each other ``` -------------------------------- ### Kotlin Inline Class Example Source: https://github.com/kotlin-hands-on/kotlin-swift-interopedia/blob/main/docs/classesandinterfaces/Inline classes.md Demonstrates the creation and basic usage of an inline class in Kotlin. Inline classes wrap a single value without runtime performance costs. The example shows a simple inline class `InlineClass` wrapping an `Int` and its instantiation in a `main` function. ```Kotlin @JvmInline value class InlineClass(val arg1: Int) { } fun main(){ //No instantiation of the class InlineClass happens, at runtime inlineClass contains just Int. val inlineClass = InlineClass(1) } ``` -------------------------------- ### Kotlin Companion Objects to Swift Source: https://github.com/kotlin-hands-on/kotlin-swift-interopedia/blob/main/README.md Demonstrates accessing members of Kotlin companion objects from Swift. Explicit access is required through the 'companion' auxiliary object. ```Swift ClassWithCompanionObject.companion.CONST_VAL_EXAMPLE ``` -------------------------------- ### Kotlin Example Class Usage Source: https://github.com/kotlin-hands-on/kotlin-swift-interopedia/blob/main/docs/functionsandproperties/Functions returning function type.md An example class in Kotlin demonstrating the usage of the `returnLambda` and `returnParametrizedLambda` functions within its `example` method. ```kotlin class FunctionReturnsLambdaExample() { fun example() { returnLambda()() returnParametrizedLambda()("123") println("FunctionReturnsLambdaExample: All ok") } } ``` -------------------------------- ### Calling Kotlin Classes and Functions from Swift Source: https://github.com/kotlin-hands-on/kotlin-swift-interopedia/blob/main/README.md Demonstrates how to instantiate Kotlin classes and call their methods directly from Swift code. This is a fundamental aspect of Kotlin-Swift interoperability. ```Swift SimpleClass().simpleFunction() ``` -------------------------------- ### Kotlin Objects to Swift Source: https://github.com/kotlin-hands-on/kotlin-swift-interopedia/blob/main/README.md Explains how to access Kotlin objects from Swift. This is done via a shared auxiliary object, allowing access to properties and methods. ```Swift MyKotlinObject.shared.myProperty ``` -------------------------------- ### Kotlin Constructors with Default Arguments in Swift Source: https://github.com/kotlin-hands-on/kotlin-swift-interopedia/blob/main/README.md Similar to functions, all arguments must be explicitly provided when calling Kotlin constructors with default arguments from Swift. ```Swift // All arguments must be specified for Kotlin constructors with default arguments when called from Swift. // let instance = KotlinClassWithDefaults(param1: value1, param2: value2) ``` -------------------------------- ### Opt-in for Experimental @ObjCName Annotation Source: https://github.com/kotlin-hands-on/kotlin-swift-interopedia/blob/main/docs/overview/ObjCName.md Provides the necessary Kotlin code to opt-in to the experimental @ObjCName annotation. This setup is required to use the annotation in your project. ```kotlin sourceSets { all { languageSettings.optIn("kotlin.experimental.ExperimentalObjCName") } } ``` -------------------------------- ### Kotlin Star Projection Example Source: https://github.com/kotlin-hands-on/kotlin-swift-interopedia/blob/main/docs/generics/Star projection.md This snippet demonstrates how to use star projection in Kotlin with a generic class. It shows a function `someStarProjection` that accepts a generic type with an unknown type argument (`*`) and provides an example of calling this function. ```Kotlin class MyGeneric(val data: T) { val state: T get() = data fun someStarProjection(myGeneric: MyGeneric<*>) { println("myGeneric: ${myGeneric}") } } fun starProjectionExample() { val myGeneric = MyGeneric(1) myGeneric.someStarProjection(myGeneric) myGeneric.someStarProjection(MyGeneric("11")) } ``` -------------------------------- ### Kotlin Collections with Basic Types in Swift Source: https://github.com/kotlin-hands-on/kotlin-swift-interopedia/blob/main/README.md Collections holding basic Kotlin types, with the exception of `String`, require a wrapper to be correctly handled in Swift. ```Swift // Collections with basic types (except String) need a wrapper. // let kotlinIntArray = KotlinArray(array: [1, 2, 3]) // Example wrapper usage ``` -------------------------------- ### Kotlin Constructors in Swift Source: https://github.com/kotlin-hands-on/kotlin-swift-interopedia/blob/main/README.md Swift can instantiate Kotlin classes by calling their constructors. This allows for the creation of Kotlin objects within a Swift environment. ```Swift // Example of calling a Kotlin constructor from Swift // let kotlinObject = KotlinClass(constructorParameter: value) ``` -------------------------------- ### Swift Extension and Example Function for Refined Kotlin Code Source: https://github.com/kotlin-hands-on/kotlin-swift-interopedia/blob/main/docs/overview/ShouldRefineInSwift.md Provides a Swift extension for the 'Person' interface to access the 'namePair' property with a more idiomatic Swift name 'name'. Includes an example function 'shouldRefineInSwiftExample' demonstrating its usage. ```swift extension Person { var name: (firstName: String, lastName: String) { let namePair = __namePair return (namePair.first! as String, namePair.second! as String) } } func shouldRefineInSwiftExample(){ let authorNames = RealPerson().name print("Author is: \(authorNames.firstName) \(authorNames.lastName)") } ``` -------------------------------- ### Accessing Kotlin Top-Level Functions in Swift Source: https://github.com/kotlin-hands-on/kotlin-swift-interopedia/blob/main/README.md Explains how to access Kotlin top-level functions from Swift. These functions are typically accessed through a generated wrapper class. ```Swift TopLevelFunctionKt.topLevelFunction() ``` -------------------------------- ### Refining Kotlin Declarations with @ShouldRefineInSwift Source: https://github.com/kotlin-hands-on/kotlin-swift-interopedia/blob/main/README.md Explains the use of the experimental @ShouldRefineInSwift annotation, which suggests replacing a Kotlin declaration with a Swift wrapper for better idiomatic integration. ```Kotlin import objc.ShouldRefineInSwift @ShouldRefineInSwift fun complexKotlinOperation(input: Int): String { // This operation might be better implemented or wrapped in Swift return "Result for \(input)" } ``` -------------------------------- ### Kotlin Sealed Classes to Swift Source: https://github.com/kotlin-hands-on/kotlin-swift-interopedia/blob/main/README.md Explains the generation of sealed classes in Swift. A class with heirs is produced, and switch statements require a default case. SKIE can enhance interop. ```Swift // A class with heirs is generated // Passing to a switch statement requires a default case ``` -------------------------------- ### Kotlin DSL with Functions and Receivers Source: https://github.com/kotlin-hands-on/kotlin-swift-interopedia/blob/main/docs/moreaboutfunctions/Functions with receivers.md Demonstrates how to create a Domain Specific Language (DSL) in Kotlin using functions with receivers. This example defines a DSL for managing experiments, allowing for a concise and readable way to define experiment configurations. ```kotlin @DslMarker annotation class DslMarkerExample data class Experiment(val key: String, val description: String) @DslMarkerExample class ExperimentsDsl() { val experimentList: MutableList = mutableListOf() fun enable(experiment: Experiment) { experimentList += experiment } } @DslMarkerExample class Dsl() { val experimentsDsl: ExperimentsDsl = ExperimentsDsl() fun experiments(block: ExperimentsDsl.() -> Unit = {}) { experimentsDsl.block() } } fun example() { val dsl = Dsl().apply { experiments { enable(Experiment(key = "key1", description = "desc1")) } } } ``` -------------------------------- ### Kotlin Constructor with Default Arguments Source: https://github.com/kotlin-hands-on/kotlin-swift-interopedia/blob/main/docs/moreaboutfunctions/Constructors with default arguments.md Shows how to define a Kotlin class with default values for constructor parameters, allowing for optional argument specification during instantiation. The example demonstrates creating an instance by only providing the required parameter. ```kotlin class ConstructorWithDefaultArgumentsClass( val param1: String, val param2: Int = 300, val param3: Boolean = false ) fun constructorWithDefaultArgumentsExample() { ConstructorWithDefaultArgumentsClass(param1 = "123") } ``` -------------------------------- ### Kotlin Extension Properties over Platform Classes to Swift Source: https://github.com/kotlin-hands-on/kotlin-swift-interopedia/blob/main/README.md Explains the implementation of Kotlin extension properties over platform classes in Swift. A wrapper class is generated with a function to access the property, taking the class object as input. ```Swift // A wrapper class appears with a function that accepts an object of the desired class. ``` -------------------------------- ### Kotlin Optional Basic Types in Swift Source: https://github.com/kotlin-hands-on/kotlin-swift-interopedia/blob/main/README.md Certain basic Kotlin types, when optional, necessitate mapping into special optional types in Swift to handle nullability correctly. ```Swift // Optional basic type mapping: // var optionalIntValue: Int32? = nil // Example of an optional Int32 ``` -------------------------------- ### Kotlin Extension Functions over Platform Classes to Swift Source: https://github.com/kotlin-hands-on/kotlin-swift-interopedia/blob/main/README.md Details how Kotlin extension functions over platform classes are handled in Swift. A wrapper class is generated containing the function, which accepts the desired class object. ```Swift // A wrapper class appears with a function that accepts an object of the desired class. ``` -------------------------------- ### Kotlin Interfaces to Swift Source: https://github.com/kotlin-hands-on/kotlin-swift-interopedia/blob/main/README.md Details how Kotlin interfaces are translated to Swift protocols. Value properties in Kotlin interfaces become 'var' in Swift stubs. ```Swift // The interface has become @protocol // Xcode turns val property into var when generating the stubs ``` -------------------------------- ### Using @ObjCName Annotation for Kotlin Declarations Source: https://github.com/kotlin-hands-on/kotlin-swift-interopedia/blob/main/README.md Illustrates the use of the experimental @ObjCName annotation to provide custom Objective-C and Swift names for Kotlin constructs without altering the original Kotlin code. ```Kotlin import objc.ObjCName @ObjCName(swiftName = "MyCustomSwiftClass") class MyKotlinClass @ObjCName(swiftName = "myCustomSwiftFunction") fun myKotlinFunction() { // ... } ``` -------------------------------- ### Kotlin Functions with Overloads in Swift Source: https://github.com/kotlin-hands-on/kotlin-swift-interopedia/blob/main/README.md Calling Kotlin functions with overloads from Swift might present peculiarities, especially concerning the use of parameter names. ```Swift // Swift code for calling overloaded Kotlin functions would depend on the specific signatures. // Example: // let result1 = kotlinClassInstance.functionWithOverload(param1: value1) // let result2 = kotlinClassInstance.functionWithOverload(paramA: valueA, paramB: valueB) ``` -------------------------------- ### Kotlin Basic Types in Swift Source: https://github.com/kotlin-hands-on/kotlin-swift-interopedia/blob/main/README.md Basic Kotlin data types may require mapping for integer types and the `Char` type to ensure compatibility and correct representation in Swift. ```Swift // Basic type mapping examples: // let intValue: Int32 = 10 // Assuming Int32 mapping for Kotlin Int // let charValue: Character = 'a' // Assuming Character mapping for Kotlin Char ``` -------------------------------- ### Swift String Type Conversion Source: https://github.com/kotlin-hands-on/kotlin-swift-interopedia/blob/main/docs/types/Basic types.md Demonstrates how Kotlin's String type is converted to Swift's String type without additional mappings, showing examples of passing String values between the two languages. ```swift func stringTypeExample(stringType: String) { let types = PrimitiveTypesClass() let _: String = types.stringType(s: "123") let _: String = types.stringType(s: stringType) } ``` -------------------------------- ### Kotlin Functions with Default Arguments in Swift Source: https://github.com/kotlin-hands-on/kotlin-swift-interopedia/blob/main/README.md When calling Kotlin functions with default arguments from Swift, all arguments must be explicitly provided. For improved interop with default arguments, consider using libraries like SKIE. ```Swift // When calling from Swift, all arguments must be specified, even if they have defaults in Kotlin. // let result = kotlinClassInstance.functionWithDefaultArgs(arg1: value1, arg2: value2, arg3: value3) ``` -------------------------------- ### Kotlin Functions with Lambda Arguments Source: https://github.com/kotlin-hands-on/kotlin-swift-interopedia/blob/main/docs/functionsandproperties/Functions expecting lambda arguments.md This snippet shows Kotlin functions designed to accept lambda expressions as arguments. It includes examples for functions with a single lambda, multiple lambdas, a lambda with parameters, and a lambda returning Unit. ```kotlin // FunctionWithLambdaArgs.kt fun funcWithLambda(calculation: () -> Int): Int { return 100 + calculation() } fun funcWithSeveralLambdas( calculation: () -> Int, formatting: (String) -> String ): String { val calculationResult = calculation() return formatting(calculationResult.toString()) } fun funcWithParametrizedLambda(parametrizedLambda: (String) -> String): String { return "FunctionWithLambdaArgs.funcWithParametrizedLambda(resultFromLambda: ${parametrizedLambda("paramForLambda")})" } fun funcWithUnitLambda(unitLambda: () -> Unit) { println("FunctionWithLambdaArgs.funcWithUnitLambda() begin") unitLambda() println("FunctionWithLambdaArgs.funcWithUnitLabmda() end") } ``` -------------------------------- ### Kotlin Extension Properties for Companion Objects of Platform Classes to Swift Source: https://github.com/kotlin-hands-on/kotlin-swift-interopedia/blob/main/README.md Addresses the limitations of accessing Kotlin extension properties for companion objects of platform classes in Swift. While a property exists in the .h file, it's not usable in Swift. ```Swift // There is a property in the .h file, but in Swift it’s impossible to use. ``` -------------------------------- ### Kotlin Flows to Swift Source: https://github.com/kotlin-hands-on/kotlin-swift-interopedia/blob/main/README.md Explains the translation of Kotlin Flows to Swift. Flows are converted to callbacks or async/await. Generic type arguments are lost. Libraries like SKIE and KMP-NativeCoroutines can enhance interop and cancellation. ```Swift // Translated into callback, experimentally - into async / await // Generic type arguments are lost. // Libraries like SKIE and KMP-NativeCoroutines can be used to improve the interop and provide cancellation support. ``` -------------------------------- ### Swift Usage of Renamed Kotlin Constructs Source: https://github.com/kotlin-hands-on/kotlin-swift-interopedia/blob/main/docs/overview/ObjCName.md Shows how to use the Kotlin constructs that have been renamed using the @ObjCName annotation from Swift. This example illustrates calling the Swift-idiomatic function with its renamed parameter. ```swift let array = MySwiftArray() let index = array.index(of: "element") ``` -------------------------------- ### Swift DSL with Functions as Parameters Source: https://github.com/kotlin-hands-on/kotlin-swift-interopedia/blob/main/docs/moreaboutfunctions/Functions with receivers.md Illustrates how Kotlin's functions with receivers are represented in Swift as functions with parameters. This example shows a similar DSL structure for managing experiments, but adapted to Swift's syntax and parameter handling. ```swift private func dslBlock(block: (Dsl) -> Dsl) -> Dsl { var dsl = Dsl() dsl = block(dsl) return dsl } func example(){ dslBlock { dsl in dsl.experiments { e in e.enable(experiment: Experiment(key: "key1", description: "param123")) } return dsl } } ``` -------------------------------- ### Handling Kotlin Exceptions in Swift Source: https://github.com/kotlin-hands-on/kotlin-swift-interopedia/blob/main/README.md Details how exceptions thrown by Kotlin functions are handled in Swift. Undeclared exceptions can crash the app, while declared exceptions are converted to NSError and require explicit handling. ```Swift // Example of handling a declared exception (assuming it's converted to NSError) try { // Call Kotlin function that might throw an exception } catch let error as NSError { // Handle the NSError print("Caught error: \(error.localizedDescription)") } ``` -------------------------------- ### Swift: Set MutableSet Example Source: https://github.com/kotlin-hands-on/kotlin-swift-interopedia/blob/main/docs/types/Mutable, immutable collections.md Demonstrates interoperability with Kotlin's Set and MutableSet types in Swift. It shows how to initialize Swift Sets from arrays, pass them to Kotlin functions, and cast mutable Kotlin sets to Swift Sets. ```swift func setMutableSetExample(){ var mutableSet: Set = Set(arrayLiteral: 1, 2, 3) let notMutableSet: Set = Set(arrayLiteral: 1, 2, 3) mutableSet = MutableImmutableCollectionsKt.setType(set: mutableSet) let _ = MutableImmutableCollectionsKt.setType(set: notMutableSet) let _ = MutableImmutableCollectionsKt.mutableSetType(set: KotlinMutableSet(set: mutableSet)) let _ = MutableImmutableCollectionsKt.mutableSetType(set: KotlinMutableSet(set: notMutableSet)) } ``` -------------------------------- ### Kotlin Sealed Interface Example Source: https://github.com/kotlin-hands-on/kotlin-swift-interopedia/blob/main/docs/classesandinterfaces/Sealed interfaces.md Defines a sealed interface in Kotlin with nested interfaces representing different cases. Includes a function that uses a `when` expression to demonstrate exhaustive checking of all sealed interface implementations. ```Kotlin sealed interface SealedInterfaces { interface First : SealedInterfaces { fun firstFunctionExample(): String } interface Second : SealedInterfaces { fun secondFunctionExample(): String } } fun sealedInterfaceExample(sie: SealedInterfaces) { when (sie) { is SealedInterfaces.First -> { sie.firstFunctionExample() } is SealedInterfaces.Second -> { sie.secondFunctionExample() } } } ``` -------------------------------- ### Kotlin Mutable and Immutable Collections in Swift Source: https://github.com/kotlin-hands-on/kotlin-swift-interopedia/blob/main/README.md Mutability of Kotlin collections is managed using `let` and `var` keywords in Swift. Additional mappings are necessary for mutable collections to ensure correct behavior. ```Swift // Mutability is handled by Swift's let/var. Mutable collections may need extra mapping. // let immutableList: KotlinList = ... // var mutableList: KotlinMutableList = ... // Requires specific mapping ``` -------------------------------- ### Kotlin Fun Interface Example Source: https://github.com/kotlin-hands-on/kotlin-swift-interopedia/blob/main/docs/classesandinterfaces/Fun interfaces.md Shows how to define and use a Kotlin 'fun interface' with a lambda expression for concise anonymous class creation. This interface has a single abstract method. ```Kotlin fun interface FunInterfaceExample { fun singleFunctionInInterface(funInterfaceExample: String): String } interface NotFunInterface { fun singleFunctionInInterface(funInterfaceExample: String): String } fun example() { val notFun = object : NotFunInterface { override fun singleFunctionInInterface(funInterfaceExample: String): String { return "return" } } val listener = FunInterfaceExample { println("it: ${it}") "some return value" } } ``` -------------------------------- ### Kotlin Data Classes to Swift Source: https://github.com/kotlin-hands-on/kotlin-swift-interopedia/blob/main/README.md Details the conversion of autogenerated functions from Kotlin data classes to Swift. Functions like 'copy', 'equals', and 'toString' are mapped to 'doCopy', 'isEquals', and 'description' respectively. Destructuring is not supported. ```Swift // copy to doCopy // equals to isEquals // toString to description ``` -------------------------------- ### Kotlin Suspend Functions to Swift Source: https://github.com/kotlin-hands-on/kotlin-swift-interopedia/blob/main/README.md Covers the translation of Kotlin suspend functions to Swift. They are typically converted to callbacks, with experimental support for async/await. Libraries like SKIE and KMP-NativeCoroutines can improve interop and cancellation. ```Swift // Translated into callback, experimentally - into async / await // Libraries like SKIE and KMP-NativeCoroutines can be used to improve the interop and provide cancellation support. ``` -------------------------------- ### Kotlin Bounded Generics Example Source: https://github.com/kotlin-hands-on/kotlin-swift-interopedia/blob/main/docs/generics/Bounded generics.md Demonstrates a generic class in Kotlin with a type parameter T restricted to a specific superclass 'ForStricted'. It shows how instances can be created with subtypes of 'ForStricted' and highlights that attempting to use an incompatible type will result in a compilation error. ```kotlin open class ForStricted class ChildStricted : ForStricted() class StrictedGeneric(val data: T) { fun fetch(): T { return data } } private fun example() { val s1 = StrictedGeneric(ForStricted()) val s2 = StrictedGeneric(ChildStricted()) // val s3 = StrictedGeneric("123") // Doesn't compile } ``` -------------------------------- ### Kotlin Top-level Properties in Swift Source: https://github.com/kotlin-hands-on/kotlin-swift-interopedia/blob/main/README.md Top-level read-only (`val`) and mutable (`var`) properties in Kotlin are accessed through a generated wrapper class. For example, `topLevelProperty` is accessed via `TopLevelPropertyKt.topLevelProperty`. ```Swift // Example of accessing a top-level Kotlin property from Swift // let topLevelValue = TopLevelPropertyKt.topLevelProperty // TopLevelMutablePropertyKt.topLevelProperty = newTopLevelValue ``` -------------------------------- ### Kotlin Enum Classes to Swift Source: https://github.com/kotlin-hands-on/kotlin-swift-interopedia/blob/main/README.md Describes the handling of Kotlin enum classes in Swift. No direct enum equivalent is generated; instead, an object with static elements is created. A default case is required in switch expressions. SKIE can improve interop. ```Swift // No equivalent enum is generated on the Swift side // Default case must be specified in a switch expression // An object with static elements is generated ``` -------------------------------- ### Swift: Collections Mutability Example Source: https://github.com/kotlin-hands-on/kotlin-swift-interopedia/blob/main/docs/types/Mutable, immutable collections.md Demonstrates how to use mutable and immutable collections in Swift when interacting with Kotlin code. It shows assigning Kotlin collections to Swift 'var' and 'let' variables and passing them to a Kotlin function. ```swift func collectionsMutabilityExample() { var mutableList: [KotlinInt] = [1, 2, 3] let notMutableList: [KotlinInt] = [1, 2, 3] mutableList = CommonTypesKt.listType(list: mutableList) let _ = CommonTypesKt.listType(list: notMutableList) } ``` -------------------------------- ### Swift Usage with Kotlin Optional Literals Source: https://github.com/kotlin-hands-on/kotlin-swift-interopedia/blob/main/docs/types/Optional basic types.md Demonstrates how to instantiate the Kotlin `OptionalPrimitives` class from Swift using literal values for optional types. This example shows direct assignment of values, including `nil` implicitly if not provided, to the Kotlin nullable properties. ```swift func optionalTypesExample3() { let _ = OptionalPrimitives( optionalByte: 1, optionalShort: 1, optionalInt: 1, optionalLong: 1, optionalFloat: 1.0, optionalDouble: 1.0, optionalString: "123", optionalBoolean: true ) } ``` -------------------------------- ### Instantiate Kotlin Class in Swift Source: https://github.com/kotlin-hands-on/kotlin-swift-interopedia/blob/main/docs/functionsandproperties/Constructors.md Demonstrates how to create an instance of a Kotlin class from Swift. It shows the syntax for calling the constructor with named parameters, noting that primitive types are converted automatically. ```swift let _ = UsualClassConstructor(param: "123") ``` -------------------------------- ### Swift: List MutableList Example Source: https://github.com/kotlin-hands-on/kotlin-swift-interopedia/blob/main/docs/types/Mutable, immutable collections.md Shows how to pass Kotlin List and MutableList types to a Kotlin function from Swift. It demonstrates converting Swift arrays to Kotlin types and using NSMutableArray for compatibility with Kotlin's MutableList. ```swift func listMutableListExample(){ var mutableList: [KotlinInt] = [1, 2, 3] let notMutableList: [KotlinInt] = [1, 2, 3] let _ = MutableImmutableCollectionsKt.mutableListType(list: NSMutableArray(array: notMutableList)) let _ = MutableImmutableCollectionsKt.mutableListType(list: NSMutableArray(array: mutableList)) } ``` -------------------------------- ### Implement Swift Protocol based on Kotlin Interface Source: https://github.com/kotlin-hands-on/kotlin-swift-interopedia/blob/main/docs/classesandinterfaces/Interfaces.md Shows a Swift class 'InterfacesExample' that implements the protocol generated from the Kotlin interface. It demonstrates how Kotlin's 'val' properties are mapped to Swift's 'var' by default and how to handle default parameters. ```swift class InterfacesExample : Interfaces { func defaultParams(param1: String, param2: Int32) -> String { return "param1: \(param1) ; param2: \(param2)" } func functionWithParam(param1: String) -> String { return "functionWithParam: \(param1)" } func simpleFunction() -> String { return "simpleFunction()" } // From the strange `val id: String` to `var` by default. // But this can be manually replaced with `let` let id: String = "default" } let ex = InterfacesExample() print(ex.defaultParams(param1: "123", param2: 234)) print(ex.functionWithParam(param1: "abc")) print(ex.simpleFunction()) ``` -------------------------------- ### Kotlin Read-only Properties in Swift Source: https://github.com/kotlin-hands-on/kotlin-swift-interopedia/blob/main/README.md Read-only member properties (declared with `val`) in Kotlin are accessible from Swift and are treated as read-only properties. ```Swift // Example of accessing a read-only Kotlin member property from Swift // let propertyValue = kotlinClassInstance.readOnlyMemberProperty ``` -------------------------------- ### Kotlin Mutable Properties in Swift Source: https://github.com/kotlin-hands-on/kotlin-swift-interopedia/blob/main/README.md Mutable member properties (declared with `var`) in Kotlin are accessible and modifiable from Swift, behaving as mutable properties. ```Swift // Example of accessing and modifying a mutable Kotlin member property from Swift // kotlinClassInstance.mutableMemberProperty = newValue ``` -------------------------------- ### Swift Usage of Kotlin Unit and Nothing Source: https://github.com/kotlin-hands-on/kotlin-swift-interopedia/blob/main/docs/types/Unit and Nothing.md Shows how to use the converted Kotlin types (KotlinUnit and KotlinNothing) in Swift. It illustrates creating an object of KotlinUnit and calling functions, while also highlighting the inability to instantiate KotlinNothing and the behavior of functions returning Nothing. ```swift let example = UnitNothing() example.unitType(p: KotlinUnit()) //Doesn't compile - no init() function //example.nothingType(n: KotlinNothing()) print(example.returnUnit()) //Crashes app - exception //example.returnNothing() ``` -------------------------------- ### Swift Initialization with Explicit Arguments Source: https://github.com/kotlin-hands-on/kotlin-swift-interopedia/blob/main/docs/moreaboutfunctions/Constructors with default arguments.md Illustrates the Swift syntax for initializing an object that corresponds to the Kotlin class with default arguments. In Swift, all arguments, including those with default values in the equivalent Kotlin class, must be explicitly provided. ```swift ConstructorWithDefaultArgumentsClass(param1: "123", param2: 500, param3: false) ``` -------------------------------- ### Hiding Kotlin Declarations from Objective-C/Swift Source: https://github.com/kotlin-hands-on/kotlin-swift-interopedia/blob/main/README.md Demonstrates the use of the experimental @HiddenFromObjC annotation to prevent specific Kotlin declarations from being exposed to Objective-C and Swift. ```Kotlin import objc.HiddenFromObjC @HiddenFromObjC fun internalKotlinFunction() { // This function will not be visible in Swift } ``` -------------------------------- ### Swift Type Handling Source: https://github.com/kotlin-hands-on/kotlin-swift-interopedia/blob/main/docs/overview/Types.md Shows how to call Kotlin functions that handle Int, String, and custom types from Swift. It demonstrates the syntax for accessing Kotlin-generated Swift classes and objects. ```swift let intType = TypesKt.printInt(intType: 123) let stringType = TypesKt.printString(stringType: "abc") let customType = TypesKt.printCustomType(customType: CustomType(name: "Author name", surname: "Author surname")) ``` -------------------------------- ### Kotlin Class Constructor Source: https://github.com/kotlin-hands-on/kotlin-swift-interopedia/blob/main/docs/functionsandproperties/Constructors.md Defines a simple Kotlin class with a primary constructor that accepts a String parameter. This class can be instantiated from Swift. ```kotlin //UsualClassConstructor.kt class UsualClassConstructor( val param: String ) ``` -------------------------------- ### Kotlin Collections with Custom Types in Swift Source: https://github.com/kotlin-hands-on/kotlin-swift-interopedia/blob/main/README.md Collections in Kotlin that contain elements of custom types do not require any additional mappings when accessed from Swift. They are generally interoperable. ```Swift // Collections with custom types are directly interoperable. // let customObjectArray: [KotlinCustomObject] = kotlinArrayOfCustomObjects ``` -------------------------------- ### Kotlin Extension Properties over Usual Classes to Swift Source: https://github.com/kotlin-hands-on/kotlin-swift-interopedia/blob/main/README.md Details how Kotlin extension properties over usual classes are accessed in Swift. The property can be accessed directly through the class object. ```Swift // The property can be accessed through the class object. ``` -------------------------------- ### Kotlin Extension Functions over Usual Classes to Swift Source: https://github.com/kotlin-hands-on/kotlin-swift-interopedia/blob/main/README.md Describes the usage of Kotlin extension functions over usual classes in Swift. The function can be directly invoked on an object of the class. ```Swift // The function can be used on a class object. ``` -------------------------------- ### Swift: Mapping Kotlin Primitive Collections Source: https://github.com/kotlin-hands-on/kotlin-swift-interopedia/blob/main/docs/types/Collections with basic types.md Demonstrates how to map Kotlin primitive types within collections when passing them to or receiving them from Swift. It shows direct initialization and mapping using `map` for type conversion. ```swift CollectionWithPrimitiveTypesKt.intList(list: [1, 2, 3]) // ok let result2: [KotlinInt] = [1, 2, 3] + CommonTypesKt.listType(list: [1, 3, 4]) // ok // Mapping let li2: [KotlinInt] = CommonTypesKt.listType( list: intList.map({ p in KotlinInt(value: Int32(p)) }) ) ``` -------------------------------- ### Kotlin Inline Functions in Swift Source: https://github.com/kotlin-hands-on/kotlin-swift-interopedia/blob/main/README.md Kotlin inline functions are present in the header file and can be called from Swift. However, they are treated as regular functions and are not inlined at the call site. ```Swift // Inline functions are callable but not actually inlined when called from Swift. // let result = kotlinClassInstance.inlineFunction(param: value) ``` -------------------------------- ### Swift Calls to Kotlin Functions with Different Parameter Names Source: https://github.com/kotlin-hands-on/kotlin-swift-interopedia/blob/main/docs/moreaboutfunctions/Functions with overloads.md This Swift code shows how to call Kotlin functions that use different parameter names for their overloads. This method is straightforward as it aligns with Swift's parameter naming conventions, avoiding the need for underscore appending. ```swift funс example() { FunctionsWithOverloads2Kt.anotherOverload(intParam: 1) FunctionsWithOverloads2Kt.anotherOverload(longParam: 1) FunctionsWithOverloads2Kt.anotherOverload(floatParam: 1.0) } ``` -------------------------------- ### Kotlin Functions with Lambda Arguments in Swift Source: https://github.com/kotlin-hands-on/kotlin-swift-interopedia/blob/main/README.md Kotlin functions that accept lambda arguments can be called from Swift without any special handling. The lambda arguments are passed seamlessly. ```Swift // Example of calling a Kotlin function expecting a lambda from Swift // kotlinClassInstance.functionWithLambda { argument in // // Swift code to execute within the lambda // return someValue // } ``` -------------------------------- ### Kotlin Member Functions in Swift Source: https://github.com/kotlin-hands-on/kotlin-swift-interopedia/blob/main/README.md Public member functions defined in Kotlin can be directly called from Swift. However, internal or private Kotlin declarations are not accessible from Swift. ```Swift // Example of calling a public Kotlin member function from Swift // let result = kotlinClassInstance.publicMemberFunction() ``` -------------------------------- ### Kotlin Extension Function on String Source: https://github.com/kotlin-hands-on/kotlin-swift-interopedia/blob/main/docs/extensions/Extension functions over platform class.md Defines an extension function `extensionFunctionOverStringClass` for the Kotlin String class and an example function `extensionFunctionOverPlatformClassExample` that calls it. ```kotlin //ExtensionFunctionOverPlatformClass.kt fun String.extensionFunctionOverStringClass() { println(this) //Do something } fun extensionFunctionOverPlatformClassExample() { "123".extensionFunctionOverStringClass() } ``` -------------------------------- ### Kotlin Functions Expecting Lambda with Receiver in Swift Source: https://github.com/kotlin-hands-on/kotlin-swift-interopedia/blob/main/README.md Kotlin functions that expect a lambda with a receiver are transformed into regular lambdas with an explicit parameter representing the receiver when called from Swift. ```Swift // Example of calling a Kotlin function with a lambda with receiver from Swift // kotlinClassInstance.functionWithLambdaReceiver { receiverArg, lambdaArg in // // Swift code using receiverArg and lambdaArg // } ``` -------------------------------- ### Calling Kotlin Reified Function from Swift Source: https://github.com/kotlin-hands-on/kotlin-swift-interopedia/blob/main/docs/generics/Reified functions.md This Swift code demonstrates how to call the Kotlin reified function `reifiedExample` (exposed as `reifiedFunction` in Swift) and print the result. It highlights the potential for runtime crashes when using reified functions across these languages. ```swift let c = ReifiedFunctionsKt.reifiedFunction(marks: 23) print("c = \(String(describing: c))") ``` -------------------------------- ### Kotlin Functions Returning Lambdas in Swift Source: https://github.com/kotlin-hands-on/kotlin-swift-interopedia/blob/main/README.md When a Kotlin function returns a lambda, it is represented as a Swift function type (e.g., `() -> String`). This Swift function type can be directly invoked. ```Swift // Example of calling a Kotlin function that returns a lambda from Swift // let returnedLambda = kotlinClassInstance.functionReturningLambda() // let lambdaResult = returnedLambda() ``` -------------------------------- ### Kotlin Functions with Receivers in Swift Source: https://github.com/kotlin-hands-on/kotlin-swift-interopedia/blob/main/README.md Functions in Kotlin that utilize receivers are converted into functions with an added parameter in Swift, making them less convenient to use compared to native Swift functions. ```Swift // Functions with receivers in Kotlin become functions with an extra parameter in Swift. // let result = kotlinClassInstance.functionWithReceiver(receiver: receiverObject, arg: argValue) ``` -------------------------------- ### Kotlin Suspend Function Example Source: https://github.com/kotlin-hands-on/kotlin-swift-interopedia/blob/main/docs/coroutines/Suspend functions.md Defines a data class 'Thing' and a repository class 'ThingRepository' with a suspend function 'getThing' that simulates a delay and can either succeed or fail. ```kotlin data class Thing(val item: Int) class ThingRepository { suspend fun getThing(succeed: Boolean): Thing { delay(100.milliseconds) if (succeed) { return Thing(0) } else { error("oh no!") } } } ``` -------------------------------- ### Swift Call to Kotlin Extension Function Source: https://github.com/kotlin-hands-on/kotlin-swift-interopedia/blob/main/docs/extensions/Extension functions over platform class.md Shows how the Kotlin extension function on String is invoked from Swift, demonstrating the generated wrapper class `ExtensionFunctionOverPlatformClassKt`. ```swift ExtensionFunctionOverPlatformClassKt.extensionFunctionOverStringClass("123") ``` -------------------------------- ### Kotlin Unit and Nothing Types in Swift Source: https://github.com/kotlin-hands-on/kotlin-swift-interopedia/blob/main/README.md The Kotlin `Unit` type can be used similarly to `void` or as an object in Swift. The `Nothing` type in Kotlin cannot be instantiated and thus has no direct representation or usage in Swift. ```Swift // Kotlin Unit maps to Void or () in Swift. // Kotlin Nothing cannot be instantiated. ``` -------------------------------- ### Opt-in for Experimental @HiddenFromObjC Annotation in Kotlin Source: https://github.com/kotlin-hands-on/kotlin-swift-interopedia/blob/main/docs/overview/HiddenFromObjC.md Shows how to enable the experimental @HiddenFromObjC annotation in Kotlin projects. This requires opting into the 'kotlin.experimental.ExperimentalObjCRefinement' feature within the source set configuration. ```kotlin sourceSets { all { languageSettings.optIn("kotlin.experimental.ExperimentalObjCRefinement") } } ``` -------------------------------- ### Kotlin Functions with vararg Parameter in Swift Source: https://github.com/kotlin-hands-on/kotlin-swift-interopedia/blob/main/README.md Kotlin's `vararg` parameters are mapped to `KotlinArray` in Swift, not directly to Swift's variadic parameters. This requires explicit array creation or conversion. ```Swift // varargs are mapped to KotlinArray, not Swift's variadic parameters. // let kotlinArray = KotlinArray(array: [value1, value2, value3]) // let result = kotlinClassInstance.functionWithVararg(vararg: kotlinArray) ``` -------------------------------- ### Kotlin Functions with Value Class Parameter in Swift Source: https://github.com/kotlin-hands-on/kotlin-swift-interopedia/blob/main/README.md When a Kotlin function has a value class parameter, it appears in the header file, but the inline class argument is converted to a basic type for Swift compatibility. ```Swift // The value class parameter is mapped to a basic type in Swift. // let result = kotlinClassInstance.functionWithValueClass(value: basicTypeValue) ``` -------------------------------- ### Kotlin Value Class Usage Example Source: https://github.com/kotlin-hands-on/kotlin-swift-interopedia/blob/main/docs/moreaboutfunctions/Functions with value class parameter.md Demonstrates a Kotlin function that takes a value class as an argument. The value class is defined with the @JvmInline annotation and a simple integer property. The function returns a formatted string including the value class's internal data. ```kotlin //FunctionWithValueClassParameter.kt @JvmInline value class ValueClassExample(val t: Int) fun valueClassUsageExample(v: ValueClassExample): String { return "Value class usage example | ${v.t}" } ``` -------------------------------- ### Swift Calls to Kotlin Overloaded Functions Source: https://github.com/kotlin-hands-on/kotlin-swift-interopedia/blob/main/docs/moreaboutfunctions/Functions with overloads.md This Swift code demonstrates how to call Kotlin's overloaded functions. Due to Swift's parameter naming requirements for overloading, underscores are appended to parameter names to differentiate between the overloaded functions originating from Kotlin. ```swift FunctionsWithOverloadsKt.overloadFunction(param: true) // Bool FunctionsWithOverloadsKt.overloadFunction(param_: 2.0) // Double FunctionsWithOverloadsKt.overloadFunction(param__: 2.0) // Float FunctionsWithOverloadsKt.overloadFunction(param___: 2) // Int32 FunctionsWithOverloadsKt.overloadFunction(param____: 4) // Int64 FunctionsWithOverloadsKt.overloadFunction(param_____: "123") ``` -------------------------------- ### KMP-NativeCoroutines: Swift Cancellation Example Source: https://github.com/kotlin-hands-on/kotlin-swift-interopedia/blob/main/docs/coroutines/Suspend functions.md Shows how to cancel a Swift Task that is executing a Kotlin suspend function managed by KMP-NativeCoroutines. This demonstrates that KMP-NativeCoroutines provides actual cancellation support. ```swift Task { do { let result = try await asyncFunction(for: ThingRepository().getThing(succeed: true)) print("Got result: \(result)") } catch { print("Failed with error: \(error)") } }.cancel() ``` -------------------------------- ### Calling Kotlin Lambdas from Swift Source: https://github.com/kotlin-hands-on/kotlin-swift-interopedia/blob/main/docs/functionsandproperties/Functions returning function type.md Shows how to invoke Kotlin functions that return lambdas directly from Swift code. It demonstrates calling both the unit-returning lambda and the string-parameterized lambda. ```swift FunctionReturnsLambdaKt.returnLambda()() FunctionReturnsLambdaKt.returnParametrizedLambda()("123") ```