"UUIDs in 10 Languages" Part 4: Swift, Kotlin, and Elixir

    15 April 2024
    10 min read
    Tutorial
    Code examples
    uuid
    distributed-systems

    UUIDs in 10 Languages — Part 4: Swift, Kotlin, and Elixir

    Welcome to Part 4 of the "UUIDs in 10 Languages" series! This time, we're diving into Swift, Kotlin, and Elixir — three modern languages with very different styles and use cases.

    Each offers unique ways to work with UUIDs, whether you're building mobile apps or functional distributed systems.


    🍎 Swift: UUIDs in iOS/macOS Development

    Swift makes UUID handling simple and native, using UUID from the Foundation framework.

    🔧 Generate a UUID

    swift
    import Foundation
    
    let uuid = UUID()
    print("UUID: \(uuid.uuidString)")

    You can also create a UUID from a string:

    swift
    if let parsed = UUID(uuidString: "550e8400-e29b-41d4-a716-446655440000") {
        print("Valid UUID: \(parsed)")
    }

    📦 Use in Structs and Models

    swift
    struct User: Identifiable {
        let id: UUID
        let name: String
    }

    🧠 Best Practices

    • Use UUID() for in-memory and persistent identifiers
    • Use UUID().uuidString for storage or URL-safe formats
    • Don't truncate UUIDs — store the full string or convert to Base64 if needed

    🤖 Kotlin: UUIDs for Android and Multiplatform

    Kotlin supports UUIDs through JVM libraries, and newer support is emerging for Kotlin Multiplatform.

    🔧 Generate a UUID (JVM/Android)

    kotlin
    import java.util.UUID
    
    fun main() {
        val id = UUID.randomUUID()
        println("UUID: $id")
    }

    🔁 Parse and Compare

    kotlin
    val input = "550e8400-e29b-41d4-a716-446655440000"
    val parsed = UUID.fromString(input)
    
    if (parsed.version() == 4) {
        println("UUIDv4 detected")
    }

    ✅ In Spring or Ktor apps

    • Use UUIDs as entity IDs (@Id val id: UUID)
    • Kotlin + JPA supports UUID as a native type

    📦 Kotlin Multiplatform

    For kotlinx.uuid support, install the UUID library:

    kotlin
    implementation("org.jetbrains.kotlinx:kotlinx-uuid-core:0.0.6")

    And generate UUIDs:

    kotlin
    import kotlinx.uuid.UUID
    import kotlinx.uuid.generateUUID
    
    val id = generateUUID()
    println(id)

    🧪 Elixir: Functional UUIDs the Ecto Way

    Elixir offers robust UUID support through Ecto.UUID and database type integrations.

    🔧 Generate a UUID

    elixir
    uuid = Ecto.UUID.generate()
    IO.puts("UUID: #{uuid}")

    🧱 Ecto Schema Example

    elixir
    defmodule MyApp.User do
      use Ecto.Schema
      import Ecto.Changeset
    
      @primary_key {:id, :binary_id, autogenerate: true}
      schema "users" do
        field :name, :string
        timestamps()
      end
    
      def changeset(user, attrs) do
        user
        |> cast(attrs, [:name])
        |> validate_required([:name])
      end
    end

    > :binary_id maps to a UUID type in most databases (e.g., uuid in Postgres)

    💡 Cast and Validate UUIDs

    elixir
    case Ecto.UUID.cast("invalid-uuid") do
      {:ok, uuid} -> IO.inspect(uuid)
      :error -> IO.puts("Invalid UUID")
    end

    🧘 Summary of UUID APIs

    LanguageGenerateParse/ValidateDB-FriendlyNotes
    SwiftUUID()UUID(uuidString:)✅ via CoreDataNative, clean UUID string output
    KotlinUUID.randomUUID()UUID.fromString()✅ (JPA, Spring)JVM-friendly + Multiplatform lib
    ElixirEcto.UUID.generate()Ecto.UUID.cast/1✅ (binary_id)Works great with Phoenix & Ecto

    Final Thoughts

    Swift, Kotlin, and Elixir all provide solid, idiomatic UUID support — whether you're working in OOP, mobile, or functional paradigms.

    • Swift makes UUIDs simple and elegant
    • Kotlin lets you work across JVM and multiplatform environments
    • Elixir integrates UUIDs deeply into its database tooling

    Use UUIDs wisely, validate inputs, and never — ever — truncate your identifiers in a fit of front-end formatting fancy.

    📦 That wraps Part 4. See you next time for more UUID magic!

    Generate Your Own UUIDs

    Ready to put this knowledge into practice? Try our UUID generators:

    Summary

    This article explores how to generate and use UUIDs in Swift, Kotlin, and Elixir — with practical code examples and language-specific best practices. Perfect for mobile and functional developers working in distributed environments.

    TLDR;

    Learn how UUIDs are used in Swift, Kotlin, and Elixir — three very different ecosystems — with idiomatic examples and caveats.

    Key takeaways:

    • Swift uses UUID() from Foundation for easy ID generation in iOS/macOS apps
    • Kotlin supports UUIDs via java.util.UUID on JVM and UUID() in Kotlin Multiplatform
    • Elixir uses Ecto.UUID and :uuid types in schemas for seamless DB handling

    Whether you're writing mobile apps or building distributed systems, each language offers tools to handle UUIDs cleanly and securely.