Skip to content

UTM Link Builder — Swift source

Build campaign tracking URLs with utm_source, utm_medium and utm_campaign parameters. Bulk mode processes a whole list, presets and import round-trip existing tracking URLs, and a validator flags attribution-breaking values — runs entirely in your browser.

This is the Swift implementation — the same logic the interactive tool runs, in a shareable, citable form.

// utm-link-builder — campaign URL builder with canonical utm_* ordering. Language: Swift (5.9, Foundation only). Port of src/lib/utm.ts build(); lint/bulk/preset helpers live in the TypeScript/Go sources.

import Foundation

let canonical: [(field: String, queryKey: String)] = [
    ("source", "utm_source"), ("medium", "utm_medium"), ("campaign", "utm_campaign"),
    ("term", "utm_term"), ("content", "utm_content"),
]

func build(_ baseUrl: String, params: [String: String]) -> String? {
    let text = baseUrl.contains("://") ? baseUrl : "https://" + baseUrl // coerce scheme-less
    guard var comps = URLComponents(string: text), comps.host != nil else { return nil }

    // Keep every unrelated query param; drop stale utm_* ones.
    comps.queryItems = (comps.queryItems ?? []).filter { !$0.name.hasPrefix("utm_") }

    for pair in canonical {
        if let value = params[pair.field], !value.isEmpty {
            comps.queryItems?.append(URLQueryItem(name: pair.queryKey, value: value))
        }
    }
    return comps.url?.absoluteString
}

// build("example.com/page?utm_source=stale&id=7",
//       params: ["source": "twitter", "medium": "social"])
// -> "https://example.com/page?id=7&utm_source=twitter&utm_medium=social"

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →