Skip to content

Hreflang Tag Generator — Swift source

Turn a list of language versions into a valid hreflang set — locale normalization, duplicate detection and x-default handling — emitted as HTML link tags or an XML sitemap block.

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

// hreflang-tag-generator — pure locale-list validation + alternate-link
// emission (SEO/meta trio).
//
// Language: Swift (5.9+), Foundation only (no external packages — the
// hreflang grammar is pure, so nothing display-only needs to be linked)
// CosmoDev polyglot showcase port of the `hreflang-tag-generator` tool.
// Ported from src/lib/hreflang.ts — display source, part of CosmoDev's
// polyglot tool pages.

import Foundation

/// One locale/URL pair. Mirrors the TS HreflangRow interface.
struct HreflangRow {
    let locale: String
    let url: String
}

/// The field set for buildHreflang — rows plus an optional x-default URL.
struct HreflangInput {
    var rows: [HreflangRow] = []
    var xDefaultUrl: String? = nil
}

/// Diagnostics plus both emitted flavors. On failure ok is false, errors
/// lists every row-located problem, and normalized/html/sitemap are empty —
/// exactly like the TS result.
struct HreflangResult {
    let ok: Bool
    let errors: [String]
    let normalized: [HreflangRow]
    let html: String
    let sitemap: String
}

/// Normalize a locale tag to Google's hreflang grammar: ll (ISO-639-1,
/// lowercase) or ll-CC (region uppercase, ISO-3166). Case and surrounding
/// whitespace are corrected ("en-us" -> "en-US"); anything else is invalid
/// and returns nil. The Swift twin of normalizeLocale() in
/// src/lib/hreflang.ts — nil stands in for the TS null.
func normalizeLocale(_ raw: String?) -> String? {
    let t = (raw ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
    let chars = Array(t)
    let isLetter = { (c: Character) -> Bool in
        ("a"..."z").contains(c) || ("A"..."Z").contains(c)
    }
    if chars.count == 2, isLetter(chars[0]), isLetter(chars[1]) {
        return String(chars).lowercased()
    }
    if chars.count == 5, isLetter(chars[0]), isLetter(chars[1]), chars[2] == "-",
        isLetter(chars[3]), isLetter(chars[4]) {
        let lang = String(chars[0...1]).lowercased()
        let region = String(chars[3...4]).uppercased()
        return lang + "-" + region
    }
    return nil
}

/// Trim raw and return it when it starts with http:// or https://, otherwise
/// nil. Mirrors the TS validUrl() helper.
private func validUrl(_ raw: String) -> String? {
    let t = raw.trimmingCharacters(in: .whitespacesAndNewlines)
    return t.hasPrefix("http://") || t.hasPrefix("https://") ? t : nil
}

/// Validate a locale/URL table and emit both hreflang flavors. Invalid input
/// collects every error (row-located) and emits empty blocks; valid input
/// normalizes locales, preserves row order, and appends x-default last.
func buildHreflang(_ input: HreflangInput) -> HreflangResult {
    var errors: [String] = []
    var normalized: [HreflangRow] = []
    var seen = Set<String>()

    for (i, row) in input.rows.enumerated() {
        let n = i + 1
        let rawLocale = row.locale
        guard let locale = normalizeLocale(rawLocale) else {
            errors.append("Row \(n): \"\(rawLocale.trimmingCharacters(in: .whitespacesAndNewlines))\" is not a valid locale — use ll or ll-CC (e.g. en, de-AT).")
            continue
        }
        if seen.contains(locale) {
            errors.append("Row \(n): locale \"\(locale)\" is already used.")
            continue
        }
        if row.url.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
            errors.append("Row \(n): URL is required.")
            continue
        }
        guard let url = validUrl(row.url) else {
            errors.append("Row \(n): URL must start with http:// or https://.")
            continue
        }
        seen.insert(locale)
        normalized.append(HreflangRow(locale: locale, url: url))
    }

    var xDefault: String? = nil
    if let xd = input.xDefaultUrl, !xd.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
        xDefault = validUrl(xd)
        if xDefault == nil {
            errors.append("x-default: URL must start with http:// or https://.")
        }
    }

    if !errors.isEmpty {
        return HreflangResult(ok: false, errors: errors, normalized: [], html: "", sitemap: "")
    }

    var htmlLines = normalized.map {
        "<link rel=\"alternate\" href=\"\($0.url)\" hreflang=\"\($0.locale)\" />"
    }
    var sitemapLines = normalized.map {
        "    <xhtml:link rel=\"alternate\" hreflang=\"\($0.locale)\" href=\"\($0.url)\"/>"
    }
    if let xd = xDefault {
        htmlLines.append("<link rel=\"alternate\" href=\"\(xd)\" hreflang=\"x-default\" />")
        sitemapLines.append("    <xhtml:link rel=\"alternate\" hreflang=\"x-default\" href=\"\(xd)\"/>")
    }

    return HreflangResult(
        ok: true,
        errors: [],
        normalized: normalized,
        html: htmlLines.joined(separator: "\n"),
        sitemap: sitemapLines.joined(separator: "\n"))
}

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 →