### Extension with Setup and Public Update Functions Source: https://realm.github.io/SwiftLint/extension_access_modifier.html An extension containing a default-scoped setup function and a public update function. This is a non-triggering example. ```swift extension Foo { func setup() {} public func update() {} } ``` -------------------------------- ### Triggering: Missing tearDown for setUp Source: https://realm.github.io/SwiftLint/balanced_xctest_lifecycle.html This example triggers the rule because `setUp` is implemented without a corresponding `tearDown` method. ```swift final class ↓FooTests: XCTestCase { override func setUp() {} } ``` -------------------------------- ### Non-Triggering Example: JustBeforeEach Block Source: https://realm.github.io/SwiftLint/quick_discouraged_call.html This example shows a 'justBeforeEach' block within a 'describe' block that is compliant with the `quick_discouraged_call` rule. It represents valid setup logic. ```swift class TotoTests: QuickSpec { override func spec() { describe("foo") { justBeforeEach { let foo = Foo() foo.toto() } } } } ``` -------------------------------- ### Mint Installation Source: https://realm.github.io/SwiftLint/index.html Install SwiftLint using the Mint package manager. ```bash mint install realm/SwiftLint ``` -------------------------------- ### Non-Triggering Example: BeforeEach Block Source: https://realm.github.io/SwiftLint/quick_discouraged_call.html This example demonstrates a 'beforeEach' block within a 'describe' block that is considered valid by the `quick_discouraged_call` rule. It shows setup code that does not trigger the lint. ```swift class TotoTests: QuickSpec { override func spec() { describe("foo") { beforeEach { let foo = Foo() foo.toto() } } } } ``` -------------------------------- ### Homebrew Installation Source: https://realm.github.io/SwiftLint/index.html Install SwiftLint using the Homebrew package manager. ```bash brew install swiftlint ``` -------------------------------- ### Example with(code:) Method Source: https://realm.github.io/SwiftLint/Structs/Example.html Returns a new `Example` instance with the provided code, leaving other properties unchanged. ```swift func with(code: String) -> Example ``` -------------------------------- ### Example focused() Method Source: https://realm.github.io/SwiftLint/Structs/Example.html Marks the current example as focused for debugging purposes only. Returns a new `Example` instance. ```swift public func focused() -> Example ``` -------------------------------- ### Example Initializer Source: https://realm.github.io/SwiftLint/Structs/Example.html Initializes a new Example with the specified code, file, and line, along with various testing configurations. ```APIDOC ## init(_:configuration:testMultiByteOffsets:testWrappingInComment:testWrappingInString:testDisableCommand:testOnLinux:testOnWindows:file:line:excludeFromDocumentation:) ### Description Create a new Example with the specified code, file, and line. ### Parameters - **code** (String) - Required - The contents of the example. - **configuration** ([String : any Sendable]?) - Optional - The untyped configuration to apply to the rule, if deviating from the default configuration. - **testMultiByteOffsets** (Bool) - Optional - Whether the example should be tested by prepending multibyte grapheme clusters. Defaults to true. - **testWrappingInComment** (Bool) - Optional - Whether test shall verify that the example wrapped in a comment doesn’t trigger. Defaults to true. - **testWrappingInString** (Bool) - Optional - Whether tests shall verify that the example wrapped into a string doesn’t trigger. Defaults to true. - **testDisableCommand** (Bool) - Optional - Whether tests shall verify that the disabled rule (comment in the example) doesn’t trigger. Defaults to true. - **testOnLinux** (Bool) - Optional - Whether the example should be tested on Linux. Defaults to true. - **testOnWindows** (Bool) - Optional - Whether the example should be tested on Windows. Defaults to true. - **file** (StaticString) - Optional - The path to the file where the example is located. Defaults to the file where this initializer is called. - **line** (UInt) - Optional - The line in the file where the example is located. Defaults to the line where this initializer is called. - **excludeFromDocumentation** (Bool) - Optional - Defaults to false. ``` -------------------------------- ### Triggering: Missing setUp for class func tearDown Source: https://realm.github.io/SwiftLint/balanced_xctest_lifecycle.html This example triggers the rule because a class method `tearDown` is implemented without a corresponding class method `setUp`. ```swift final class ↓FooTests: XCTestCase { class func tearDown() {} } ``` -------------------------------- ### Extend Example with Hashable Conformance Source: https://realm.github.io/SwiftLint/Structs/Example.html Conforms the `Example` struct to the `Hashable` protocol. ```swift extension Example: Hashable ``` -------------------------------- ### Example File Property Source: https://realm.github.io/SwiftLint/Structs/Example.html The static string path to the file where the example was created. Defaults to the file where the initializer is called. ```swift public private(set) var file: StaticString { get } ``` -------------------------------- ### Shared Examples Block Source: https://realm.github.io/SwiftLint/quick_discouraged_call.html Shows how to define shared examples with a let declaration. ```swift class TotoTests: QuickSpec { override func spec() { sharedExamples("foo") { let foo = ↓Foo() } } } ``` -------------------------------- ### Triggering Example: TODO with Prefix Source: https://realm.github.io/SwiftLint/todo.html This example triggers the 'todo' rule because the comment starts with the required prefix '// ↓TODO:'. ```swift // ↓TODO: ``` -------------------------------- ### Declare Example Struct Source: https://realm.github.io/SwiftLint/Structs/Example.html Defines the basic structure for an example, which is `Sendable`. ```swift public struct Example : Sendable ``` -------------------------------- ### Example Line Property Source: https://realm.github.io/SwiftLint/Structs/Example.html The line number in the file where the example was created. ```swift public var line: UInt ``` -------------------------------- ### Extend Example with Comparable Conformance Source: https://realm.github.io/SwiftLint/Structs/Example.html Conforms the `Example` struct to the `Comparable` protocol. ```swift extension Example: Comparable ``` -------------------------------- ### Triggering example: Computed property with explicit 'get' Source: https://realm.github.io/SwiftLint/implicit_getter.html This example triggers the `implicit_getter` rule because the 'get' keyword is explicitly used for a computed property where it is not necessary. The '↓' indicates the start of the violation. ```swift class Foo { var foo: Int { ↓get { return 20 } } } ``` -------------------------------- ### Initialize Example Source: https://realm.github.io/SwiftLint/Structs/Example.html Creates a new `Example` instance with specified code, configuration, and testing options. Defaults are provided for most parameters. ```swift init(_ code: String, configuration: [String: any Sendable]? = nil, testMultiByteOffsets: Bool = true, testWrappingInComment: Bool = true, testWrappingInString: Bool = true, testDisableCommand: Bool = true, testOnLinux: Bool = true, testOnWindows: Bool = true, file: StaticString = #filePath, line: UInt = #line, excludeFromDocumentation: Bool = false) ``` -------------------------------- ### with(code:) Source: https://realm.github.io/SwiftLint/Structs/Example.html Returns a new Example instance with the provided code, leaving other properties unchanged. ```APIDOC ## with(code:) ### Description Returns the same example, but with the `code` that is passed in. ### Parameters - **code** (String) - Required - the new code to use in the modified example ``` -------------------------------- ### Triggering example: Extension property with explicit 'get' Source: https://realm.github.io/SwiftLint/implicit_getter.html This example triggers the `implicit_getter` rule for a computed property within an extension that explicitly uses the 'get' keyword. The '↓' indicates the start of the violation. ```swift extension Foo { var bar: Bool { ↓get { _bar } } } ``` -------------------------------- ### Triggering example: Static computed property with explicit 'get' Source: https://realm.github.io/SwiftLint/implicit_getter.html This example triggers the `implicit_getter` rule for a static computed property that explicitly uses the 'get' keyword. The '↓' indicates the start of the violation. ```swift class Foo { static var foo: Int { ↓get { return 20 } } } ``` -------------------------------- ### Triggering Example: Documentation Comment TODO Source: https://realm.github.io/SwiftLint/todo.html This documentation comment triggers the 'todo' rule, starting with the required prefix '/** ↓TODO:'. ```swift /** ↓TODO: */ ``` -------------------------------- ### Triggering example: Computed property with explicit 'get' in a class with Objective-C method Source: https://realm.github.io/SwiftLint/implicit_getter.html This example triggers the `implicit_getter` rule for a computed property with an explicit 'get' keyword, even when the class also contains an Objective-C method. The '↓' indicates the start of the violation. ```swift class Foo { @objc func bar() {} var foo: Int { ↓get { return 20 } } } ``` -------------------------------- ### Triggering example: Subscript with explicit 'get' Source: https://realm.github.io/SwiftLint/implicit_getter.html This example triggers the `implicit_getter` rule for a subscript that explicitly uses the 'get' keyword. The '↓' marks the beginning of the violation. ```swift class Foo { subscript(i: Int) -> Int { ↓get { return 20 } } } ``` -------------------------------- ### SwiftLint Configuration Example Source: https://realm.github.io/SwiftLint/index.html This is a comprehensive example of a .swiftlint.yml configuration file. It demonstrates how to disable default rules, enable opt-in rules, specify included and excluded paths, and configure rule severities and parameters like line length and type name constraints. It also shows how to set the reporter. ```yaml # By default, SwiftLint uses a set of sensible default rules you can adjust. Find all the available rules # by running `swiftlint rules` or visiting https://realm.github.io/SwiftLint/rule-directory.html. # Rules turned on by default can be disabled. disabled_rules: - colon - comma - control_statement # Rules turned off by default can be enabled. opt_in_rules: - empty_count # Alternatively, specify all rules explicitly by uncommenting this option and removing the above two. # only_rules: # - empty_parameters # - vertical_whitespace # Rules only run by `swiftlint analyze`. These are all opt-in. analyzer_rules: - explicit_self # Case-sensitive paths to include during linting. Directory paths supplied on the # command line will be ignored. Wildcards are supported. included: - Sources # Case-sensitive paths to ignore during linting. Takes precedence over `included`. Wildcards # are supported. excluded: - Carthage - Pods - Sources/ExcludedFolder - Sources/ExcludedFile.swift - Sources/*/ExcludedFile.swift # If true, SwiftLint will not fail if no lintable files are found. allow_zero_lintable_files: false # If true, SwiftLint will treat all warnings as errors. strict: false # If true, SwiftLint will treat all errors as warnings. lenient: false # The path to a baseline file, which will be used to filter out detected violations. baseline: Baseline.json # The path to save detected violations to as a new baseline. write_baseline: Baseline.json # If true, SwiftLint will check for updates after linting or analyzing. check_for_updates: true # Configurable rules can be customized. All rules support setting their severity level. force_cast: warning # implicitly force_try: severity: warning # explicitly # Rules that have both warning and error levels can set just the warning level implicitly. line_length: 110 # To set both levels implicitly, use an array. type_body_length: - 300 # warning - 400 # error # To set both levels explicitly, use a dictionary. file_length: warning: 500 error: 1200 # Naming rules can set warnings/errors for `min_length` and `max_length`. Additionally, they can # set excluded names and allowed symbols. type_name: min_length: 4 # warning max_length: # warning and error warning: 40 error: 50 excluded: i(Phone|Pad|Pod) # regex pattern allowed_symbols: ["_"] identifier_name: min_length: error: 4 # only error excluded: # excluded via string array - id - URL - GlobalAPIKey # The default reporter (SwiftLint's output format) can be configured as `checkstyle`, `codeclimate`, `csv`, # `emoji`, `github-actions-logging`, `gitlab`, `html`, `json`, `junit`, `markdown`, `relative-path`, `sarif`, # `sonarqube`, `summary`, or `xcode` (default). reporter: "xcode" ``` -------------------------------- ### Shared Examples with Assignment Source: https://realm.github.io/SwiftLint/quick_discouraged_call.html Demonstrates an assignment within a shared examples block. ```swift class TotoTests: QuickSpec { override func spec() { sharedExamples("foo") { bar = ↓foo() } } } ``` -------------------------------- ### Triggering example: Global variable with explicit 'get' Source: https://realm.github.io/SwiftLint/implicit_getter.html This example triggers the `implicit_getter` rule for a global variable that explicitly uses the 'get' keyword. The '↓' marks the beginning of the violation. ```swift var foo: Int { ↓get { return 20 } } ``` -------------------------------- ### Build from Source Source: https://realm.github.io/SwiftLint/index.html Instructions to build SwiftLint from source. Requires Bazel and a recent Swift toolchain. ```bash make install ``` -------------------------------- ### Triggering example: Computed property with explicit 'get' (compact) Source: https://realm.github.io/SwiftLint/implicit_getter.html This compact example also triggers the `implicit_getter` rule due to the explicit 'get' keyword. The '↓' marks the beginning of the violation. ```swift class Foo { var foo: Int { ↓get{ return 20 } } } ``` -------------------------------- ### Example Equality Operator Source: https://realm.github.io/SwiftLint/Structs/Example.html Compares two `Example` instances for equality. ```swift public static func == (lhs: Example, rhs: Example) -> Bool ``` -------------------------------- ### Triggering UIDevice.init direct initialization with let Source: https://realm.github.io/SwiftLint/discouraged_direct_init.html Shows a triggering example of direct UIDevice.init() assigned to a let constant. ```swift let foo = ↓UIDevice.init() ``` -------------------------------- ### CodeBlockVisitor.init(configuration:file:) Source: https://realm.github.io/SwiftLint/Classes/CodeBlockVisitor.html Initializes a new instance of the CodeBlockVisitor with the specified configuration and file. ```APIDOC ## CodeBlockVisitor.init(configuration:file:) ### Description Initializes a new instance of the CodeBlockVisitor with the specified configuration and file. ### Method `init` ### Parameters - **configuration** (Configuration) - The rule configuration to use. - **file** (SwiftLintFile) - The SwiftLintFile to process. ``` -------------------------------- ### Non-Triggering Availability Checks Source: https://realm.github.io/SwiftLint/deployment_target.html These examples demonstrate correct usage of `@available` attributes and `#available` checks that meet or exceed the deployment target. No specific setup is required beyond standard Swift syntax. ```swift @available(iOS 12.0, *) class A {} ``` ```swift @available(iOSApplicationExtension 13.0, *) class A {} ``` ```swift @available(watchOS 4.0, *) class A {} ``` ```swift @available(watchOSApplicationExtension 4.0, *) class A {} ``` ```swift @available(swift 3.0.2) class A {} ``` ```swift class A {} ``` ```swift if #available(iOS 10.0, *) {} ``` ```swift if #available(iOS 10, *) {} ``` ```swift guard #available(iOS 12.0, *) else { return } ``` ```swift #if #unavailable(iOS 15.0) {} ``` ```swift #guard #unavailable(iOS 15.0) {} else { return } ``` -------------------------------- ### Stack Start Index Source: https://realm.github.io/SwiftLint/Structs/Stack.html Provides the starting index for collection-based access to the stack elements. ```swift public var startIndex: Int { get } ``` -------------------------------- ### Subscript with explicit 'get throws' block Source: https://realm.github.io/SwiftLint/implicit_getter.html This example demonstrates a subscript that explicitly uses 'get throws'. The explicit 'get' is required here due to the 'throws' keyword, and therefore it does not violate the `implicit_getter` rule. ```swift struct Test { subscript(value: Int) -> Int { get throws { if value == 0 { throw NSError() } else { return value } } } } ``` -------------------------------- ### Non-Triggering Example: Excluded Method Source: https://realm.github.io/SwiftLint/unneeded_override.html Functions listed in the 'excluded_methods' configuration are ignored by the rule, even if they are unneeded overrides. This example excludes 'setUp'. ```swift // // excluded_methods: ["setUp"] // class FooTestCase: XCTestCase { override func setUp() { super.setUp() } } ``` -------------------------------- ### Triggering Bundle direct initialization with let Source: https://realm.github.io/SwiftLint/discouraged_direct_init.html Illustrates a triggering example of direct Bundle initialization assigned to a let constant. ```swift let foo = ↓Bundle() ``` -------------------------------- ### Triggering UIDevice direct initialization with let Source: https://realm.github.io/SwiftLint/discouraged_direct_init.html Shows a triggering example of direct UIDevice initialization assigned to a let constant. ```swift let foo = ↓UIDevice() ``` -------------------------------- ### Example Test On Windows Property Source: https://realm.github.io/SwiftLint/Structs/Example.html A boolean flag indicating whether the example should be tested on Windows. Defaults to true. ```swift public private(set) var testOnWindows: Bool { get } ``` -------------------------------- ### Triggering Bundle.init direct initialization with let Source: https://realm.github.io/SwiftLint/discouraged_direct_init.html Illustrates a triggering example of direct Bundle.init() assigned to a let constant. ```swift let foo = ↓Bundle.init() ``` -------------------------------- ### Use NSSize Constructor Source: https://realm.github.io/SwiftLint/legacy_constructor.html Demonstrates the preferred way to initialize NSSize using its constructor. ```swift NSSize(width: 10, height: 10) ``` ```swift NSSize(width: aWidth, height: aHeight) ``` -------------------------------- ### Protocol property with 'get' only Source: https://realm.github.io/SwiftLint/implicit_getter.html This example shows a protocol requirement for a read-only property. The 'get' keyword is explicitly used, which is standard for protocol definitions and does not trigger the `implicit_getter` rule. ```swift protocol Foo { var foo: Int { get } } ``` -------------------------------- ### Example Struct Properties Source: https://realm.github.io/SwiftLint/Structs/Example.html This section details the properties of the Example struct, which are used to capture code and context information for linting rule examples. ```APIDOC ## Example Struct Properties ### Description Properties that capture code and context information for an example of a triggering or non-triggering style. ### Properties - **code** (String): The contents of the example. - **configuration** ([String : any Sendable]?): The untyped configuration to apply to the rule, if deviating from the default configuration. - **testMultiByteOffsets** (Bool): Whether the example should be tested by prepending multibyte grapheme clusters. - **testOnLinux** (Bool): Whether the example should be tested on Linux. - **testOnWindows** (Bool): Whether the example should be tested on Windows. - **file** (StaticString): The path to the file where the example was created. - **line** (UInt): The line in the file where the example was created. ``` -------------------------------- ### Incorrect Property Accessor Order in Protocol Source: https://realm.github.io/SwiftLint/protocol_property_accessors_order.html This example violates the rule by using `set get` instead of the required `get set` order for property accessors in a protocol. SwiftLint will flag this. ```swift protocol Foo { var bar: String { ↓set get } } ``` -------------------------------- ### Use CGSize Constructor Source: https://realm.github.io/SwiftLint/legacy_constructor.html Demonstrates the preferred way to initialize CGSize using its constructor. ```swift CGSize(width: 10, height: 10) ``` ```swift CGSize(width: aWidth, height: aHeight) ``` -------------------------------- ### Example Test On Linux Property Source: https://realm.github.io/SwiftLint/Structs/Example.html A boolean flag indicating whether the example should be tested on Linux. Defaults to true. ```swift public private(set) var testOnLinux: Bool { get } ``` -------------------------------- ### Array Extension for Example Elements Source: https://realm.github.io/SwiftLint/Extensions.html Extends Array to work with elements of type Example. ```swift public extension Array where Element == Example ``` -------------------------------- ### Triggering: Subscript with set before get Source: https://realm.github.io/SwiftLint/computed_accessors_order.html This example violates the rule by placing the setter before the getter in a subscript. ```swift class Foo { subscript(i: Int) -> Int { ↓set { print(i) } get { return 20 } } } ``` -------------------------------- ### Initializer: init(configuration:) Source: https://realm.github.io/SwiftLint/Protocols/Rule.html Initializes a rule with a given configuration. Throws an error if the configuration format is invalid. ```swift init(configuration: Any) throws ``` -------------------------------- ### Non-Triggering: Balanced setUp and tearDownWithError Source: https://realm.github.io/SwiftLint/balanced_xctest_lifecycle.html A test case using a standard `setUp` method and `tearDownWithError`. ```swift final class FooTests: XCTestCase { override func setUp() {} override func tearDownWithError() throws {} } ``` -------------------------------- ### Triggering Examples of Function Body Length Source: https://realm.github.io/SwiftLint/function_body_length.html These examples show function bodies that exceed the default line count limits, triggering the function_body_length rule. The '↓' symbol indicates the start of the violation. ```swift // // warning: 2 // ↓func f() { let x = 0 let y = 1 let z = 2 } ``` ```swift // // warning: 2 // class C { ↓deinit { let x = 0 let y = 1 let z = 2 } } ``` ```swift // // warning: 2 // class C { ↓init() { let x = 0 let y = 1 let z = 2 } } ``` ```swift // // warning: 2 // class C { ↓subscript() -> Int { let x = 0 let y = 1 return x + y } } ``` ```swift // // warning: 2 // struct S { subscript() -> Int { ↓get { let x = 0 let y = 1 return x + y } ↓set { let x = 0 let y = 1 let z = 2 } ↓willSet { let x = 0 let y = 1 let z = 2 } } } ``` -------------------------------- ### Use NSPoint Constructor Source: https://realm.github.io/SwiftLint/legacy_constructor.html Demonstrates the preferred way to initialize NSPoint using its constructor. ```swift NSPoint(x: 10, y: 10) ``` ```swift NSPoint(x: xValue, y: yValue) ``` -------------------------------- ### Non-Triggering Example: AroundEach Block Source: https://realm.github.io/SwiftLint/quick_discouraged_call.html This example demonstrates an 'aroundEach' block within a 'describe' block that adheres to the `quick_discouraged_call` rule. It shows a valid way to use aroundEach for test setup or teardown. ```swift class TotoTests: QuickSpec { override func spec() { describe("foo") { aroundEach { let foo = Foo() foo.toto() } } } } ``` -------------------------------- ### init(fromAny:context:) Source: https://realm.github.io/SwiftLint/Extensions/String.html Initializes a String from any type, with a given context. This is typically used during configuration loading. ```APIDOC ## init(fromAny:context:) ### Description Initializes a String from any type, with a given context. ### Declaration Swift ```swift public init(fromAny value: Any, context ruleID: String) throws(Issue) ``` ``` -------------------------------- ### Asynchronous computed property with explicit getter Source: https://realm.github.io/SwiftLint/implicit_getter.html This example shows an asynchronous computed property with an explicit 'get' block. While the 'get' keyword is present, the asynchronous nature requires it, and thus it does not trigger the `implicit_getter` rule. ```swift class DatabaseEntity { var isSynced: Bool { get async { await database.isEntitySynced(self) } } } ``` -------------------------------- ### init(configuration:file:legacyFunctions:) Source: https://realm.github.io/SwiftLint/Classes/LegacyFunctionVisitor.html Initializes a LegacyFunctionVisitor with the specified configuration, file, and a mapping of legacy functions to their rewrite strategies. ```APIDOC ## init(configuration:file:legacyFunctions:) ### Description Initializer for a `ViolationsSyntaxVisitor`. ### Method `init` ### Parameters #### Path Parameters - `configuration` (Configuration) - Required - Configuration of a rule. - `file` (SwiftLintFile) - Required - File from which the syntax tree stems from. - `legacyFunctions` ([String: LegacyFunctionRewriteStrategy]) - Required - A dictionary mapping legacy function names to their rewrite strategies. ``` -------------------------------- ### SwiftLint Docker Execution Output Source: https://realm.github.io/SwiftLint/index.html Example output demonstrating SwiftLint running inside a Docker container, showing linting progress and results. ```text $ docker run -it -v `pwd`:`pwd` -w `pwd` ghcr.io/realm/swiftlint:latest Linting Swift files in current working directory Linting 'RuleDocumentation.swift' (1/490) ... Linting 'YamlSwiftLintTests.swift' (490/490) Done linting! Found 0 violations, 0 serious in 490 files. ``` -------------------------------- ### Triggering: Computed property with set before mutating get Source: https://realm.github.io/SwiftLint/computed_accessors_order.html This example violates the rule by placing the setter before a mutating getter. ```swift class Foo { var foo: Int { ↓set { print(newValue) } mutating get { return 20 } } } ``` -------------------------------- ### Triggering Example: Public IBOutlet Source: https://realm.github.io/SwiftLint/private_outlet.html Example of an IBOutlet that violates the rule by not being private. ```swift class Foo { @IBOutlet ↓var label: UILabel? } ``` -------------------------------- ### Triggering: Extension property with set before get Source: https://realm.github.io/SwiftLint/computed_accessors_order.html This example violates the rule by placing the setter before the getter in an extension property. ```swift extension Foo { var bar: Bool { ↓set { print(bar) } get { _bar } } } ``` -------------------------------- ### Triggering Example: Three QuickSpec Classes Source: https://realm.github.io/SwiftLint/single_test_class.html This example triggers the rule due to the presence of three classes inheriting from QuickSpec. ```swift ↓class FooTests: QuickSpec { } ↓class BarTests: QuickSpec { } ↓class TotoTests: QuickSpec { } ``` -------------------------------- ### Triggering: Global variable with set before get Source: https://realm.github.io/SwiftLint/computed_accessors_order.html This example violates the rule by placing the setter before the getter in a global variable. ```swift var foo: Int { ↓set { print(newValue) } get { return 20 } } ``` -------------------------------- ### Image from Asset Catalog Source: https://realm.github.io/SwiftLint/accessibility_label_for_image.html This example shows how to create an `Image` from an asset catalog. For accessibility, consider adding a label if the image conveys important information. ```swift struct MyView: View { var body: some View { ↓Image("my-image") .resizable(true) .frame(width: 48, height: 48) } } ``` -------------------------------- ### Triggering: Computed property with set before get Source: https://realm.github.io/SwiftLint/computed_accessors_order.html This example violates the rule by placing the setter before the getter in a computed property. ```swift class Foo { var foo: Int { ↓set { print(newValue) } get { return 20 } } } ``` -------------------------------- ### Switch with Tuple and Leading Let Binding Source: https://realm.github.io/SwiftLint/pattern_matching_keywords.html A switch statement with a tuple case that starts with a 'let' binding. This is a non-triggering example. ```swift switch foo { case (let x, y): break } ``` -------------------------------- ### Non-Triggering Example: Getter and Setter Order Swapped Source: https://realm.github.io/SwiftLint/unused_setter_value.html Demonstrates that the order of `get` and `set` blocks does not affect the correct usage of `newValue`. ```swift var aValue: String { set { Persister.shared.aValue = newValue } get { return Persister.shared.aValue } } ``` -------------------------------- ### init(value:) Source: https://realm.github.io/SwiftLint/Structs/SwiftLintSyntaxMap.html Creates a SwiftLintSyntaxMap from the raw SyntaxMap obtained by SourceKitten. ```APIDOC ## init(value:) ### Description Creates a `SwiftLintSyntaxMap` from the raw `SyntaxMap` obtained by SourceKitten. ### Declaration Swift ```swift public init(value: SyntaxMap) ``` ### Parameters - `value` (SyntaxMap) - The raw `SyntaxMap` obtained by SourceKitten. ``` -------------------------------- ### Triggering: Static computed property with set before get Source: https://realm.github.io/SwiftLint/computed_accessors_order.html This example violates the rule by placing the setter before the getter in a static computed property. ```swift class Foo { static var foo: Int { ↓set { print(newValue) } get { return 20 } } } ``` -------------------------------- ### Non-Triggering Example: Set Initialization Source: https://realm.github.io/SwiftLint/redundant_type_annotation.html These examples demonstrate various ways to initialize a Set with inferred types, which are not flagged by the rule. ```swift var set: Set = Set([]) ``` ```swift var set: Set = Set.init([]) ``` ```swift var set = Set([]) ``` ```swift var set = Set.init([]) ``` -------------------------------- ### Triggering Example: fit Source: https://realm.github.io/SwiftLint/quick_discouraged_focused_test.html This example shows a focused test case using `fit`, which is discouraged. ```swift class TotoTests: QuickSpec { override func spec() { ↓fit("foo") { } } } ``` -------------------------------- ### Default Implementation: init(fromAny:context:) Source: https://realm.github.io/SwiftLint/Protocols/AcceptableByConfigurationElement.html Provides a default implementation for initializing the object from configuration data. ```swift init(fromAny _: Any, context _: String) throws(Issue) ``` -------------------------------- ### Non-Triggering Example: NSImage Initializer Source: https://realm.github.io/SwiftLint/discouraged_object_literal.html Provides an example of initializing an NSImage using its named initializer with a variable. ```swift let image = NSImage(named: aVariable) ``` -------------------------------- ### Non-triggering: Basic property initialization Source: https://realm.github.io/SwiftLint/self_in_property_initialization.html This example shows a simple property initialization without any target-action setup, which does not trigger the lint rule. ```swift class View: UIView { let button: UIButton = { return UIButton() }() } ``` -------------------------------- ### Triggering Examples for Prefer Key Path Source: https://realm.github.io/SwiftLint/prefer_key_path.html These examples show code that triggers the 'prefer_key_path' rule, indicating where key paths can be used instead of closures for property access. ```swift f.map ↓{ $0.a } ``` ```swift f.filter ↓{ $0.a } ``` ```swift f.first ↓{ $0.a } ``` ```swift f.contains ↓{ $0.a } ``` ```swift f.contains(where: ↓{ $0.a }) ``` ```swift // // restrict_to_standard_functions: false // f(↓{ $0.a }) ``` ```swift // // restrict_to_standard_functions: false // f(a: ↓{ $0.b }) ``` ```swift // // restrict_to_standard_functions: false // f(a: ↓{ a in a.b }, x) ``` ```swift f.map ↓{ a in a.b.c } ``` ```swift f.allSatisfy ↓{ (a: A) in a.b } ``` ```swift f.first ↓{ (a b: A) in b.c } ``` ```swift f.contains ↓{ $0.0.a } ``` ```swift f.compactMap ↓{ $0.a.b.c.d } ``` ```swift f.flatMap ↓{ $0.a.b } ``` ```swift // // restrict_to_standard_functions: false // let f: (Int) -> Int = ↓{ $0.bigEndian } ``` ```swift transform = ↓{ $0.a } ``` -------------------------------- ### Non-Triggering Example: Initializer with 6 Parameters Source: https://realm.github.io/SwiftLint/function_parameter_count.html This example shows an initializer with six parameters, which is within the default warning threshold. ```swift init(a: Int, b: Int, c: Int, d: Int, e: Int, f: Int) {} ``` -------------------------------- ### init(fromPath:) Source: https://realm.github.io/SwiftLint/Structs/Baseline.html Initializes a Baseline by reading violations from a specified file path. ```APIDOC ## init(fromPath:) ### Description Creates a `Baseline` from a saved file. ### Declaration ```swift public init(fromPath path: URL) throws ``` ### Parameters #### Path Parameters - **path** (URL) - Required - The path to read from. ``` -------------------------------- ### Nested computed property with explicit getter and setter Source: https://realm.github.io/SwiftLint/implicit_getter.html This example shows a nested struct with a computed property that explicitly uses 'get' and 'set'. The outer computed property returns the value from this nested property. The explicit 'get' in the nested struct is allowed. ```swift class Foo { var foo: Int { struct Bar { var bar: Int { get { return 1 } set { _ = newValue } } } return Bar().bar } } ``` -------------------------------- ### Triggering Example: Multiple QuickSpec Classes Source: https://realm.github.io/SwiftLint/single_test_class.html This example triggers the rule because it contains two classes inheriting from QuickSpec in the same file. ```swift ↓class FooTests: QuickSpec { } ↓class BarTests: QuickSpec { } ``` -------------------------------- ### Non-Triggering: Balanced setUp and tearDown Source: https://realm.github.io/SwiftLint/balanced_xctest_lifecycle.html A typical XCTestCase class with both `setUp` and `tearDown` methods implemented. ```swift final class FooTests: XCTestCase { override func setUp() {} override func tearDown() {} } ``` -------------------------------- ### Non-Triggering Example: Basic Initializer Source: https://realm.github.io/SwiftLint/modifier_order.html Demonstrates correct ordering of 'public', 'required', and 'convenience' for an initializer. ```swift public class Foo { public required convenience init() {} } ``` -------------------------------- ### Triggering Example: Block Comment TODO Source: https://realm.github.io/SwiftLint/todo.html This multi-line block comment triggers the 'todo' rule, starting with the required prefix '/* ↓TODO:'. ```swift /* ↓TODO: */ ``` -------------------------------- ### Triggering example with filter and isEmpty Source: https://realm.github.io/SwiftLint/contains_over_filter_is_empty.html This example shows a triggering case using `filter(where:).isEmpty`. ```swift let result = ↓myList.filter(where: { $0 % 2 == 0 }).isEmpty ``` -------------------------------- ### Triggering Example: Tuple with Named Elements Source: https://realm.github.io/SwiftLint/large_tuple.html A tuple with three named elements (start, end, value) triggers the Large Tuple rule. ```swift let foo: ↓(start: Int, end: Int, value: String) ``` -------------------------------- ### Populating Dictionary with reduce(into:) Source: https://realm.github.io/SwiftLint/reduce_into.html Shows how to populate a dictionary using `reduce(into:)`. ```swift let foo = values.reduce(into: [String: Int]()) { result, value in result["\(value)"] = value } ``` ```swift let foo = values.reduce(into: Dictionary.init()) { result, value in result["\(value)"] = value } ``` ```swift let foo = values.↓reduce([String: Int]()) { result, value in var result = result result["\(value)"] = value return result } ``` ```swift let bar = values.↓reduce(Dictionary.init()) { result, value in var result = result result["\(value)"] = value return result } ``` -------------------------------- ### Protocol Property with Getter Only Source: https://realm.github.io/SwiftLint/protocol_property_accessors_order.html This example demonstrates a valid protocol property declaration that only includes a getter. This is acceptable as it does not violate the `get set` order rule. ```swift protocol Foo { var bar: String { get } } ``` -------------------------------- ### Use UIOffset Constructor Source: https://realm.github.io/SwiftLint/legacy_constructor.html Demonstrates the preferred way to initialize UIOffset using its constructor. ```swift UIOffset(horizontal: 0, vertical: 10) ``` ```swift UIOffset(horizontal: horizontal, vertical: vertical) ``` -------------------------------- ### Triggering on Multiple Extensions and Classes Source: https://realm.github.io/SwiftLint/file_types_order.html Example showing SwiftLint's analysis of multiple extensions and class definitions. ```swift // Supporting Types protocol TestViewControllerDelegate { func didPressTrackedButton() } // Extensions ↓extension TestViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } } class TestViewController: UIViewController {} // Extensions extension TestViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } } ``` -------------------------------- ### Computed property with initializer and getter Source: https://realm.github.io/SwiftLint/implicit_getter.html This example demonstrates a computed property that has an explicit initializer and a getter. The `@storageRestrictions` attribute is used here, and the explicit 'get' is allowed. ```swift class Foo { var _foo: Int var foo: Int { @storageRestrictions(initializes: _foo) init { _foo = newValue } get { _foo } } } ``` -------------------------------- ### init(style:) Source: https://realm.github.io/SwiftLint/Classes/CodeIndentingRewriter.html Initializer accepting an indentation style. ```APIDOC ## Initializer: init(style:) ### Description Initializer accepting an indentation style. ### Declaration Swift ```swift public init(style: IndentationStyle = .indentSpaces(4)) ``` ### Parameters - **style** (IndentationStyle) - Indentation style. The default is indentation by 4 spaces. ``` -------------------------------- ### Triggering: Function call with multiline arguments starting on new line Source: https://realm.github.io/SwiftLint/multiline_arguments_brackets.html This example violates the rule because the first argument is on a new line, but the opening bracket is not. ```swift foo(↓param1: "Param1", param2: "Param2", param3: "Param3" ) ``` -------------------------------- ### Use UIEdgeInsets Constructor Source: https://realm.github.io/SwiftLint/legacy_constructor.html Demonstrates the preferred way to initialize UIEdgeInsets using its constructor. ```swift UIEdgeInsets(top: 0, left: 0, bottom: 10, right: 10) ``` ```swift UIEdgeInsets(top: aTop, left: aLeft, bottom: aBottom, right: aRight) ``` -------------------------------- ### Subscript with explicit getter and setter Source: https://realm.github.io/SwiftLint/implicit_getter.html This example demonstrates a subscript with both 'get' and 'set' keywords explicitly defined. This is a valid use case and does not trigger the `implicit_getter` rule. ```swift class Foo { subscript(i: Int) -> Int { get { return 3 } set { _abc = newValue } } } ``` -------------------------------- ### Triggering example with filter and isEmpty (shorthand) Source: https://realm.github.io/SwiftLint/contains_over_filter_is_empty.html This example shows a triggering case using `filter {}.isEmpty`. ```swift let result = ↓myList.filter { $0 % 2 == 0 }.isEmpty ``` -------------------------------- ### Example Code Property Source: https://realm.github.io/SwiftLint/Structs/Example.html Represents the actual code content of the example. It is publicly accessible with a private setter. ```swift public private(set) var code: String { get } ``` -------------------------------- ### Non-Triggering Examples for Closing Brace Spacing Source: https://realm.github.io/SwiftLint/closing_brace.html Examples that adhere to the spacing rules, showing correct usage. ```swift [].map({ }) ``` ```swift [].map( { } ) ``` -------------------------------- ### Correct Property Accessor Order in Protocol Source: https://realm.github.io/SwiftLint/protocol_property_accessors_order.html This example shows the correct way to declare a property with both getter and setter accessors in a protocol. Ensure `get set` is used. ```swift protocol Foo { var bar: String { get set } } ``` -------------------------------- ### Computed property with getter and _modify block Source: https://realm.github.io/SwiftLint/implicit_getter.html This example shows a computed property that uses a 'get' block along with a '_modify' block. This is a valid pattern and does not trigger the `implicit_getter` rule. ```swift class Foo { var foo: Int { get { _foo } _modify { yield &_foo } } } ``` -------------------------------- ### NSImage for macOS Source: https://realm.github.io/SwiftLint/accessibility_label_for_image.html This example shows how to create an `Image` from an `NSImage` on macOS. Remember to provide accessibility labels for meaningful images. ```swift struct PreferencesView: View { var body: some View { VStack { ↓Image(nsImage: NSImage(named: "gear") ?? NSImage()) .resizable() .frame(width: 24, height: 24) Text("Settings") } } } ``` -------------------------------- ### Computed property with explicit getter and setter Source: https://realm.github.io/SwiftLint/implicit_getter.html This example shows a computed property with both 'get' and 'set' keywords explicitly defined. This is a valid use case and does not trigger the `implicit_getter` rule. ```swift class Foo { var foo: Int { get { return 3 } set { _abc = newValue } } } ``` -------------------------------- ### yaml() Method Source: https://realm.github.io/SwiftLint/Structs/RuleConfigurationOption.html Converts the configuration option into a YAML formatted string. ```swift public func yaml() -> String ``` -------------------------------- ### Valid Type Names - SwiftLint Source: https://realm.github.io/SwiftLint/type_name.html Examples of type names that comply with the type_name rule, including classes, structs, enums, and type aliases. Private types can start with an underscore. ```swift class MyType {} ``` ```swift private struct _MyType {} ``` ```swift // // excluded: ["^`.+`$"] // struct `My Struct` {} ``` ```swift enum AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA {} ``` ```swift typealias Foo = Void ``` ```swift private typealias Foo = Void ``` ```swift protocol Foo { associatedtype Bar } ``` ```swift protocol Foo { associatedtype Bar: Equatable } ``` ```swift enum MyType { case value } ``` ```swift // // validate_protocols: false // protocol P {} ``` ```swift struct SomeStruct { enum `Type` { case x, y, z } } ``` -------------------------------- ### Use CGPoint Constructor Source: https://realm.github.io/SwiftLint/legacy_constructor.html Demonstrates the preferred way to initialize CGPoint using its constructor. ```swift CGPoint(x: 10, y: 10) ``` ```swift CGPoint(x: xValue, y: yValue) ``` -------------------------------- ### Forbidding Single-Line Calls Source: https://realm.github.io/SwiftLint/multiline_call_arguments.html When `allows_single_line` is set to `false`, this example shows how the rule enforces that all arguments for a multi-line call must be placed on separate lines, starting after the opening parenthesis. ```swift // // allows_single_line: false // foo( param1: 1, param2: 2, param3: 3 ) ``` -------------------------------- ### init(fromAny:context:) Source: https://realm.github.io/SwiftLint/Extensions/Double.html Initializes a Double from any type of value, with a given context for rule identification. ```APIDOC ## init(fromAny:context:) ### Description Initializes a Double from any type of value, with a given context for rule identification. ### Declaration Swift ```swift public init(fromAny value: Any, context ruleID: String) throws(Issue) ``` ``` -------------------------------- ### Triggering Example: Enum with Invalid Generic Type Name 'type' Source: https://realm.github.io/SwiftLint/generic_type_name.html This enum declaration violates the generic type name rule due to 'type' not starting with an uppercase letter. ```swift enum Foo<↓type> {} ``` -------------------------------- ### Triggering Example: Struct with Invalid Generic Type Name 'type' Source: https://realm.github.io/SwiftLint/generic_type_name.html This struct declaration violates the generic type name rule due to 'type' not starting with an uppercase letter. ```swift struct Foo<↓type> {} ``` -------------------------------- ### Simple Context Block Source: https://realm.github.io/SwiftLint/quick_discouraged_call.html A basic example of a context block. ```swift class TotoTests: QuickSpec { override func spec() { context("foo") { let foo = ↓Foo() } } } ``` -------------------------------- ### Triggering Example: Class with Invalid Generic Type Name 'type' Source: https://realm.github.io/SwiftLint/generic_type_name.html This class declaration violates the generic type name rule due to 'type' not starting with an uppercase letter. ```swift class Foo<↓type> {} ``` -------------------------------- ### Triggering Example: FIXME with Prefix Source: https://realm.github.io/SwiftLint/todo.html This example triggers the 'todo' rule as the comment begins with the specified prefix '// ↓FIXME:'. ```swift // ↓FIXME: ``` -------------------------------- ### Use CGRect Constructor Source: https://realm.github.io/SwiftLint/legacy_constructor.html Demonstrates the preferred way to initialize CGRect using its constructor. ```swift CGRect(x: 0, y: 0, width: 10, height: 10) ``` ```swift CGRect(x: xVal, y: yVal, width: aWidth, height: aHeight) ``` -------------------------------- ### Triggering Example: Function with Invalid Generic Type Name 'type' Source: https://realm.github.io/SwiftLint/generic_type_name.html This function declaration violates the generic type name rule due to 'type' not starting with an uppercase letter. ```swift func foo<↓type>() {} ``` -------------------------------- ### Static property with inline getter Source: https://realm.github.io/SwiftLint/implicit_getter.html This example shows a static property with an inline '@inline(__always)' attribute and an explicit 'get' block. This specific pattern is allowed and does not trigger the `implicit_getter` rule. ```swift var _objCTaggedPointerBits: UInt { @inline(__always) get { return 0 } } ``` -------------------------------- ### Nested Context and BeforeEach Source: https://realm.github.io/SwiftLint/quick_discouraged_call.html Demonstrates deeply nested context blocks with a beforeEach closure for setup. ```swift class TotoTests: QuickSpec { override func spec() { describe("foo") { context("foo") { context("foo") { beforeEach { let foo = Foo() foo.toto() } it("bar") { } context("foo") { let foo = ↓Foo() } } } } } } ``` -------------------------------- ### Static computed property with explicit getter and setter Source: https://realm.github.io/SwiftLint/implicit_getter.html This example shows a static computed property that explicitly defines both 'get' and 'set' keywords. This is a valid construct and does not violate the `implicit_getter` rule. ```swift class Foo { static var foo: Int { get { return 3 } set { _abc = newValue } } } ``` -------------------------------- ### Switch with comment between case and code Source: https://realm.github.io/SwiftLint/vertical_whitespace_between_cases.html Demonstrates a non-triggering example where a comment exists between the end of one case's code and the start of the next case, with a single empty line present. ```swift switch x { case .a: print("a") // Comment case .b: print("b") } ``` -------------------------------- ### Mutating getter with defer statement Source: https://realm.github.io/SwiftLint/implicit_getter.html This example demonstrates a mutating getter that uses a 'defer' statement to increment a counter. The explicit 'get' keyword is used here, which is valid in this context and does not violate the `implicit_getter` rule. ```swift var next: Int? { mutating get { defer { self.count += 1 } return self.count } } ``` -------------------------------- ### SeverityConfiguration.init(_:) Source: https://realm.github.io/SwiftLint/Structs/SeverityConfiguration.html Initializes a SeverityConfiguration with a specified severity. ```APIDOC ## SeverityConfiguration.init(_:) ### Description Create a `SeverityConfiguration` with the specified severity. ### Declaration Swift ```swift public init(_ severity: ViolationSeverity) ``` ### Parameters #### Path Parameters - **_severity_** (ViolationSeverity) - Required - The severity that should be used when emitting violations. ``` -------------------------------- ### init(fromAny:context:) Source: https://realm.github.io/SwiftLint/Enums/AccessControlLevel.html Initializes an AccessControlLevel from any value, with a given context. ```APIDOC ## init(fromAny:context:) ### Description Initializes an `AccessControlLevel` from any value, with a given context. ### Declaration Swift ```swift public init(fromAny value: Any, context ruleID: String) throws(Issue) ``` ### Parameters - `value` (Any) - The value to initialize from. - `context` (String) - The context rule ID. ``` -------------------------------- ### Extension property with explicit getter and setter for clamping values Source: https://realm.github.io/SwiftLint/implicit_getter.html This example shows a computed property in an extension that explicitly defines 'get' and 'set' to clamp a Float value between 0 and 1. This is a valid use of explicit getters and setters. ```swift extension Float { var clamped: Float { set { self = min(1, max(0, newValue)) } get { min(1, max(0, self)) } } } ``` -------------------------------- ### init(fromAny:context:) Source: https://realm.github.io/SwiftLint/Extensions/Bool.html Initializes a Bool from any type, providing context for rule identification. ```APIDOC ## init(fromAny:context:) ### Description Initializes a Bool from any type, providing context for rule identification. This initializer is used to parse configuration values. ### Method Swift Initializer ### Signature ```swift public init(fromAny value: Any, context ruleID: String) throws(Issue) ``` ### Parameters #### Path Parameters - **value** (Any) - The value to initialize the Bool from. - **ruleID** (String) - The identifier of the rule context. ### Throws - **Issue**: Thrown if the provided value cannot be converted to a Bool. ``` -------------------------------- ### Non-Triggering QuickSpec Example Source: https://realm.github.io/SwiftLint/quick_discouraged_pending_test.html This example shows a correctly structured QuickSpec without any pending or skipped tests, demonstrating valid test organization. ```swift class TotoTests: QuickSpec { override func spec() { describe("foo") { describe("bar") { } context("bar") { it("bar") { } } it("bar") { } itBehavesLike("bar") } } } ``` -------------------------------- ### Used Import Example Source: https://realm.github.io/SwiftLint/unused_import.html Demonstrates a correctly used import statement for the Dispatch module. ```swift import Dispatch // This is used dispatchMain() ```