Compiler Protocol Init

ID

swift.compiler_protocol_init

Severity

low

Remediation Complexity

medium

Remediation Risk

low

Remediation Effort

medium

Resource

Code Smell

Language

Swift

Tags

code-smell, idiomatic

Description

Reports a manual call to one of the literal-conformance initialisers — init(arrayLiteral:), init(stringLiteral:), init(dictionaryLiteral:), init(integerLiteral:), init(floatLiteral:), init(booleanLiteral:), init(nilLiteral:), init(unicodeScalarLiteral:), init(extendedGraphemeClusterLiteral:). These exist so the compiler can synthesise literal syntax; calling them by hand is roundabout when the literal itself works.

let xs = Array(arrayLiteral: 1, 2, 3)         // FLAW
let s  = String(stringLiteral: "hello")       // FLAW

let xs: [Int]  = [1, 2, 3]                    // OK
let s : String = "hello"                      // OK

Rationale

Those initialisers come from the _ExpressibleByXxxLiteral protocol family. They’re conformance hooks — the compiler calls them when it encounters a matching literal — not public API for day-to-day construction. Spelling them out adds noise and discourages future readers from refactoring to the literal form.

Remediation

Use the literal syntax:

let xs: [Int] = [1, 2, 3]
let s: String = "hello"
let dict: [String: Int] = ["k": 1]

If you need a non-literal construction (e.g. building from a sequence), use the relevant non-literal initialiser (Array(repeating:count:), Array<Int>(other), etc.).