SwiftLint Code Specification Attributes (1)

The previous Xcode specification SwiftLint Configuration introduced the installation and use of SwiftLint

Here’s a brief description of the code rules for SwiftLint

  • Swift code specification published by Github — original text
  • Github published Swift code specification – Chinese
  • Official SwiftLint rule description

The following attributes are in alphabetical order

Rule 1: closing_brace

When using Swift 3.2 or later, the PREFERRED system’s KVO API and keypath

Identification code Enable by default Whether automatic correction is supported type
block_based_kvo To enable the no idiomatic

Official example:

// The compiler passeslet observer = foo.observe(\.value, options: [.new]) { (foo, change) in
   printClass Foo: NSObject {override func observeValue(change. NewValue)}forKeyPath keyPath: String? , of object: Any? , change: [NSKeyValueChangeKey : Any]? , context: UnsafeMutableRawPointer?) {}}Copy the code

Rule 2: class_delegate_protocol

Delegate protocols should only be class classes and can be weakly referenced.

Identification code Enable by default Whether automatic correction is supported type
class_delegate_protocol To enable the no lint

Example:

// Warning protocol FooDelegate: class {} protocol FooDelegate: class, BarDelegate {} protocol Foo {} class FooDelegate {} @objc protocol FooDelegate {} @objc(MyFooDelegate) protocol FooDelegate {} protocol FooDelegate: BarDelegate {} protocol FooDelegate: AnyObject {} protocol FooDelegate: NSObjectProtocol {} Warning protocol FooDelegate {} protocol FooDelegate: Bar {}Copy the code

Rule 3: closing_brace

Do not use Spaces like braces that contain braces

Identification code Enable by default Whether automatic correction is supported type
closing_brace To enable the yes style

Specific examples:

// Warning [1, 2].map({$0 })

[1, 2].map(
  { $0}) warning [1, 2].map({$0 } )
[1, 2].map({ $0 }   )
[1, 2].map( { $0 })
Copy the code

Rule 4: closure_end_indentation

The closing end of a closure has the same indentation as the beginning, meaning braces (usually methods) are aligned up and down, which makes code look cleaner

Identification code Enable by default Whether automatic correction is supported type
closure_end_indentation Is not enabled no style

Specific examples:

// Does not trigger closure_end_indentation [1, 2].map {$0+ 1} // Does not trigger closure_end_indentation SignalProducer(values: [1, 2, 3]). StartWithNext {numberin
       print(number)} // Does not trigger closure_end_indentationfunction{... } // Will trigger closure_end_indentation SignalProducer(values: [1, 2, 3]). StartWithNext {numberin
       print(number)} // Does not trigger closure_end_indentationfunction{... }Copy the code

Rule 5: closure_parameter_position

Closure argument position. The closure argument should be on the same line as the left side of the curly brace

Identification code Enable by default Whether automatic correction is supported type
closure_parameter_position To enable the no style

Specific examples:

/// If number and {are on the same line, no warning is triggeredlet names = [1, 2, 3]
names.forEach { (number) in
    print(number)
}

let names = [1, 2, 3]
names.map { number inClosure_parameter_position is violated and a warning is triggeredlet names = [1, 2, 3]
names.forEach { 
    (number) in
    print(number)
}

 let names = [1, 2, 3]
 names.map {
     number in
     number + 1
 }
Copy the code

Rule 6: closure_spacing

There should be a space between the {} closures, such as map({$0}).

Identification code Enable by default Whether automatic correction is supported type
closure_spacing Is not enabled yes style

Examples:

Warning map({$0 })
[].map ({ $0.description}) // Warning map({$0 })
map({ $0})
map({$0})
[].map ({$0.description     })
Copy the code

Rule 7: colon

The use of the colon, swiftLint’s colon attribute rule is simple, requiring “: There must be no space next to a defined constant, variable, etc. There must be only one space between the specified type and one more or one less space. This is a rule THAT I think should be mandatory

Identification code Enable by default Whether automatic correction is supported type
colon To enable the yes style

Specific examples:

// No warning will be triggered
let abc: String = "jun"
let abc = [1: [3: 2].3: 4]
let abc = [1: [3: 2].3: 4]

// Will trigger a warning
let jun:Void
let jun : Void
let jun :Void
let jun:   Void
Copy the code

Rule 8: comma

Use commas as long as you follow the “one step back, one step forward” rule, which is also mandatory

Identification code Enable by default Whether automatic correction is supported type
comma To enable the yes style

Specific examples:

// Do not trigger warning [a, b, c, d]Copy the code

Rule 9: compiler_protocol_init

Init is not recommended. Simple initialization is recommended

Identification code Enable by default Whether automatic correction is supported type
compiler_protocol_init To enable the no lint

Official example:

    public static let description = RuleDescription(
        identifier: "compiler_protocol_init",
        name: "Compiler Protocol Init",
        description: "The initializers declared in compiler protocols such as `ExpressibleByArrayLiteral` " +
                     "shouldn't be called directly.",
        kind: .lint,
        nonTriggeringExamples: [
            "let set: Set<Int> = [1, 2]\n"."let set = Set(array)\n"
        ],
        triggeringExamples: [
            "Let set = ↓ set (arrayLiteral: 1, 2)\n"."Let set = ↓ set.init (arrayLiteral: 1, 2)\n"])Copy the code

Rule 10: conditional_returns_on_newline

Conditional statements cannot be written on the same line. Conditional return statements should be on a new line. When a conditional return is made it should return on a line break, not on the same line

Identification code Enable by default Whether automatic correction is supported type
conditional_returns_on_newline Is not enabled no style

Specific examples:

/// SwiftLint Is not recommended, otherwise it will trigger warningif true { return }
guard true else { return} /// SwiftLint as recommendedif true {
    return
}

guard true else {
    return 
}
Copy the code

Rule 11: contains_over_first_not_nil

Functions like first cannot determine if they are nil

Identification code Enable by default Whether automatic correction is supported type
contains_over_first_not_nil Is not enabled no performance

Specific examples:

//let first = myList.first(where: { $0% 2 == 0})let first = myList.first { $0% 2 == 0} // Mylist.first {$0% 2 == 0}! = nil myList.first(where: { $0% 2 == 0})! = nilCopy the code

Rule 12: control_statement

Conditions in control statements, for, while, do, and catch statements cannot be included in ()

Identification code Enable by default Whether automatic correction is supported type
control_statement To enable the no style

Specific examples:

// It is recommendedif condition {
if(a, b) == (0, 1) {//if (condition) {
if(condition) {
if ((a || b) && (c || d)) {
Copy the code

Rule 13: custom_rules

Custom rules. This property allows you to create custom rules by providing regular expressions that optionally specify syntax type collocations, security, levels, and what information to display. This property does not currently apply to people familiar with regular expressions

Identification code Enable by default Whether automatic correction is supported type
custom_rules To enable the no style

Rule 14: cyclomatic_complexity

Cyclic complexity. The function body should be limited in complexity. This property mainly restricts the nesting of loops in conditional sentences and loop sentences. If there are too many nested loops, Warning and ERROR will be triggered in SwiftLint

Identification code Enable by default Whether automatic correction is supported type
cyclomatic_complexity To enable the no metrics

Rule 15: discarded_notification_center_observer

When using registered notifications, the returned observers should be stored so that the notifications can be removed when they are finished

Identification code Enable by default Whether automatic correction is supported type
discarded_notification_center_observer To enable the no lint

Code examples:

//
let foo = nc.addObserver(forName: .NSSystemTimeZoneDidChange, object: nil, queue: nil) { }

let foo = nc.addObserver(forName: .NSSystemTimeZoneDidChange, object: nil, queue: nil, using: { })

func foo() -> Any {
   return nc.addObserver(forName: .NSSystemTimeZoneDidChange, object: nil, queue: nil, using: { })
}


// Not recommended
nc.addObserver(forName: .NSSystemTimeZoneDidChange, object: nil, queue: nil) { }

nc.addObserver(forName: .NSSystemTimeZoneDidChange, object: nil, queue: nil, using: { })

@discardableResult func foo() -> Any {
   return nc.addObserver(forName: .NSSystemTimeZoneDidChange, object: nil, queue: nil, using: { })
}
Copy the code

Rule 16: discouraged_direct_init

Prevent the type of error caused by direct initialization. If there are class methods, use class methods to initialize (direct init is not recommended).

Identification code Enable by default Whether automatic correction is supported type
discouraged_direct_init To enable the no lint

Code examples:

// It is recommendedlet foo = UIDevice.current
let foo = Bundle.main
let foo = Bundle(path: "bar")
let foo = Bundle(identifier: "bar") // Not recommendedlet foo = UIDevice()
let foo = Bundle()
let foo = bar(bundle: Bundle(), device: UIDevice())
Copy the code

Rule 17: discouraged_optional_boolean

Optional Booleans are not recommended

Identification code Enable by default Whether automatic correction is supported type
discouraged_optional_boolean Is not enabled no idiomatic

Code examples:

Var foo: Bool var foo: [String: Bool] var foo: [Bool]let foo: Bool = trueVar foo: Bool? var foo: [String: Bool?]  var foo: [Bool?]let foo: Bool? = nil
Copy the code

Rules: 18 discouraged_object_literal

Object initialization is preferred over code block initialization

Identification code Enable by default Whether automatic correction is supported type
discouraged_object_literal Is not enabled no idiomatic

Code examples:

// Not recommendedlet white = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
letImage = left#imageLiteral(resourceName: "image.jpg")
Copy the code

Rule 19: dynamic_inline

Avoid using dynamic and @inline(_ _always) together, otherwise error is reported

Identification code Enable by default Whether automatic correction is supported type
dynamic_inline To enable the no lint

Code examples:

Class LangKe {dynamic funcmyFunction() {

    }
}

class LangKe {
    @inline(__always) func myFunction() {

    }
}

class LangKe {
    @inline(never) dynamic func myFunction() {}} @inline(_ _always) {}} @inline(_ _always) class LangKe { @inline(__always) public dynamic funcmyFunction() {}}Copy the code

Rule 20: array_init

When a sequence is converted to an array, array conversion is preferred over seq.map {$0}

Identification code Enable by default Whether automatic correction is supported type
array_init Is not enabled no lint

Official example:

    public static let description = RuleDescription(
        identifier: "array_init",
        name: "Array Init",
        description: "Prefer using Array(seq) than seq.map { $0 } to convert a sequence into an Array.",
        kind: .lint,
        
        // The following example does not trigger a warning
        nonTriggeringExamples: [
            "Array(foo)\n"."Foo. The map} {$0.0 \ n"."foo.map { $1 }\n"."foo.map { $0() }\n"."foo.map { ((), $0) }\n"."foo.map { $0! }\n"."foo.map { $0! /* force unwrap */ }\n"."foo.something { RouteMapper.map($0) }\n"].// The following example triggers a warning
        triggeringExamples: [
            "Left foo. The map ({$0}) \ n"."Left foo. The map {$0} \ n"."↓foo.map {return $0}\n"."Left foo. The map {elem in \ n" +
            " elem\n" +
            "}\n"."Left foo. The map {elem in \ n" +
            " return elem\n" +
            "}\n"."↓foo.map {(elem: String) in\n" +
                " elem\n" +
            "}\n"."↓foo.map {elem -> String in\n" +
            " elem\n" +
            "}\n".$foo.map {$0 /* a comment */}\n"])Copy the code

Rule 21: empty_count

It is recommended to use isEmpty instead of count==0

Identification code Enable by default Whether automatic correction is supported type
empty_count Is not enabled no performance

Code examples:

/// SwiftLint is not recommended for this uselet number = "long"
if number.characters.count == 0 {
    print("Empty")}else {
    print("Not empty"} /// SwiftLint recommends this formal styleif number.isEmpty {
    print("Empty")}else {
    print("Not empty")}Copy the code

Rule 22: empty_enum_arguments

When enumerations match the associated type, the parameters can be omitted if they are not used

Identification code Enable by default Whether automatic correction is supported type
empty_enum_arguments To enable the yes style

Code examples:

//SwiftLint suggests switch foo {case .bar: break
}
switch foo {
    case .bar(let x): break
}
switch foo {
    case let .bar(x): break
}
switch (foo, bar) {
    case (_, _): break
}
switch foo {
    case "bar".uppercased(): break} //SwiftLint is not recommended as switch foo {case .bar(_): break
}
switch foo {
    case .bar(): break
}
switch foo {
    case .bar(_), .bar2(_): break
}
Copy the code

Rule 23: empty_parameters

When the closure argument is empty, it is recommended to use () ->Void instead of Void ->Void

Identification code Enable by default Whether automatic correction is supported type
empty_parameters To enable the yes style

Code examples:

/// 01 does not trigger warningletABC: () -> Void func foo(completion: () -> Void) {let bcd: Void -> Void

func foo(completion: Void -> Void) {

}
Copy the code

Rules: 24 empty_parentheses_with_trailing_closure

Empty parentheses should be avoided when using trailing closures

Identification code Enable by default Whether automatic correction is supported type
empty_parentheses_with_trailing_closure To enable the yes style

Code examples:


Copy the code

Rule 25: aaa

.

Identification code Enable by default Whether automatic correction is supported type
aaa Is not enabled no style

Code examples:

// Warning [1, 2].map {$0 + 1 }
[1, 2].map({ $0 + 1 })
[1, 2].reduce(0) { $0 + The $1 }
[1, 2].map { number inNumber + 1} // Warning [1, 2] is triggered.map() { $0+ 1} [1, 2].map() {$0+ 1} [1, 2].map() { number in
   number + 1 
}
[1, 2].map(  ) { number in
   number + 1 
}
Copy the code

Rules: 26 explicit_acl

. All property and method declarations should explicitly specify the modifier key

Identification code Enable by default Whether automatic correction is supported type
explicit_acl Is not enabled no idiomatic

Official code examples:

// Non-triggered Example Internal enum A {} public final class B {} private struct C {} internal funca() { let a =  }
private struct C { letd = 5 } internal class A { deinit {} } internal protocol A { func b() var c: Enum A {} final class B {} internal struct C {let d = 5 }
public struct C { let d = 5 }
func a() {}
internal let a = 0
func b() {}
Copy the code

Rule 27: explicit_type_interface

The declared attribute should specify its type, for example: var myVar: Int = 0

Identification code Enable by default Whether automatic correction is supported type
explicit_type_interface Is not enabled no idomatic

Code examples:

Class Foo {var myVar: Int? = 0letmyLet: Int? Class Foo {myVar = 0} //let myLet = 0
}
Copy the code

Rule 28: extension_access_modifier

In custom classes, the extension extension is recommended

Identification code Enable by default Whether automatic correction is supported type
extension_access_modifier Is not enabled no idiomatic

Code examples:


Copy the code

Rules: 29 no_extension_access_modifier

Modifiers such as (Fileprivate, public) are not recommended before the extension extension

Identification code Enable by default Whether automatic correction is supported type
no_extension_access_modifier Is not enabled no idiomatic

Code examples:

Private extension String {} Public Extension String {} Open Extension String {} Internal extension String {} fileprivate extension String {}Copy the code

Rules: 30 fallthrough

Fallthrough is not recommended in switch statements

Identification code Enable by default Whether automatic correction is supported type
fallthrough To enable the no idiomatic

Code examples:

// Switch foo {case.bar,.bar2,.bar3: something()} switch foo {case .bar:
    fallthrough
case .bar2:
    something()
}
Copy the code

Rules: 31 fatal_error_message

It is recommended to have a prompt message when executing fatalError; Such as: fatalError (” Foo “)

Identification code Enable by default Whether automatic correction is supported type
fatal_error_message Is not enabled no idiomatic

Code examples:

// The recommendation is required init? (coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented"} // Required init? (coder aDecoder: NSCoder) { fatalError("")}Copy the code

Rule 32: file_header

The file header. New files should start with the same comments

Identification code Enable by default Whether automatic correction is supported type
aaa Is not enabled no style

Code examples:

/// Does not trigger warning
/// If I create a new project, in the viewController.swift file, the opening comment should be:

// ViewController.swift
// SwiftLint
//
// Created by langke on 17/1/17.
// Copyright © 2017 Langke. All rights reserved.
//Change to://
// MyViewController.swift................... Warning is emitted because the filename is not the same as the filename outside (actually testing this property on Swift 3.0 has no effect yet!!).
// SwiftLint
//
// Created by langke on 17/1/17.
/ / Copyright © 2017 langke. All rights reserved... Copyright and Created are not aligned and will trigger warning!!
//
Copy the code

Rules: 33 file_length

The number of lines in the file, exceeding 400 lines warning, exceeding 1000 lines error

Identification code Enable by default Whether automatic correction is supported type
file_length To enable the no metrics

Code examples:

Copy the code

Rule 34: first_where

It is not recommended to use.first directly after using the filter and map functions

Identification code Enable by default Whether automatic correction is supported type
first_where Is not enabled no performance

Official code examples:

    public static let description = RuleDescription(
        identifier: "first_where",
        name: "First Where",
        description: "Prefer using `.first(where:)` over `.filter { }.first` in collections.",
        kind: .performance,
        
        // No warning will be triggered
        nonTriggeringExamples: [
            "kinds.filter(excludingKinds.contains).isEmpty && kinds.first == .identifier\n"."myList.first(where: { $0 % 2 == 0 })\n"."match(pattern: pattern).filter { $0.first == .identifier }\n"."(myList.filter { $0 == 1 }.suffix(2)).first\n"].// This will trigger a warning
        triggeringExamples: [
            "↓myList.filter { $0 % 2 == 0 }.first\n"."↓ mylist.filter ({$0%2 == 0}).first\n"."Left myList. Map {$0 + 1}. The filter (2 = = 0} {$0%). The first \ n"."Left myList. Map {$0 + 1}. The filter (2 = = 0} {$0%). The first? .something()\n"."Left myList. Filter (someFunction.) first \ n"."↓ mylist. filter({$0%2 == 0})\ n.feather \n"."(↓myList.filter { $0 == 1 }).first\n"])Copy the code

Rule 35: for_where

In a for loop, it is not recommended to use a single if statement or loop variable only once. Instead, use where or if{}else{} statements

Identification code Enable by default Whether automatic correction is supported type
for_where To enable the no idiomatic

Code examples:

//for user in users where user.id == 1 { }
for user in users {
   if let id = user.id { }
}
for user in users {
   if var id = user.id { }
}
for user in users {
   if user.id == 1 { } else{}}for user in users {
   if user.id == 1 { }
   print(user)
}
for user in users {
   let id = user.id
   if id == 1 { }
}
for user in users {
   ifUser. id == 1 && user.age > 18 {}} // This is not recommendedfor user in users {
   if user.id == 1 { return true}}Copy the code

Rules: 36 force_cast

Direct strong solution types are not recommended

Identification code Enable by default Whether automatic correction is supported type
force_cast To enable the no idiomatic

Code examples:

NSNumber() as? Int // not recommended NSNumber() ↓as! IntCopy the code

Rules: 37 force_try

For methods that throw an exception (throws), try! Strong solution

Identification code Enable by default Whether automatic correction is supported type
force_try To enable the no idiomatic

Code examples:

Func myFunction() throws {} ///do{try myFunction()} catch {} myFunction()Copy the code

Rules: 38 force_unwrapping

Forcibly unpack/unpack. We know that when a type is optional, we need to force unpacking (also called implicit unpacking) when we get a value, usually by adding a “! “after a variable or desired constant, type, etc. However, SwiftLint recommends that forced unpacking should be avoided, otherwise warning will be given

Identification code Enable by default Whether automatic correction is supported type
force_unwrapping Is not enabled no idiomatic

Code examples:

/// Warning navigationController! .pushViewController(myViewController, animated:true)

let url = NSURL(string: "http://www.baidu.com")!
print(url)

returncell! /// Does not trigger warning navigationController? .pushViewController(myViewController, animated:true)
Copy the code

Rule 39: function_body_length

The length of the function body should not span too many lines, more than 40 lines to warning, more than 100 lines to error

Identification code Enable by default Whether automatic correction is supported type
function_body_length To enable the no metrics

Code examples:

Copy the code

Rules: 40 function_parameter_count

  • The number of function arguments (except init) should be small, not too many. Swiftlint specifies that functions with more than 5 arguments should be sent to warning, and functions with more than 8 arguments should be sent to error
  • Note:function_parameter_count: errorThis does not change its warnings or errors; the property cannot be modified, but can be disabled
Identification code Enable by default Whether automatic correction is supported type
function_parameter_count To enable the no metrics

Code examples:

Copy the code

Rules: 41 generic_type_name

Generic type names can contain only alphanumeric characters, starting with a capital letter, and ranging in length from 1 to 20 characters

Identification code Enable by default Whether automatic correction is supported type
generic_type_name Is not enabled no idiomatic

Code examples:

Func foo<T>() {} func foo<T>() -> T {} func foo<T, U>(param: U) -> T {} func foo<T: Hashable, U: Rule>(param: U) - > {T} / / do not recommend writing func foo < T_Foo > () {} func foo < T, U_Foo > (param: U_Foo) -> T {} func foo<TTTTTTTTTTTTTTTTTTTTT>() {} func foo<type> () {}Copy the code

Rule 42: identifier_name

Variable identifier names should contain only alphanumeric characters and start with a lowercase letter or should contain only uppercase letters. In the above exceptions, variable names may begin with a capital letter when they are declared static and immutable. Variable names should not be too long or too short

Identification code Enable by default Whether automatic correction is supported type
identifier_name To enable the no style

Official examples:

Internal struct IdentifierNameRuleExamples {/ / not trigger the error of staticlet nonTriggeringExamples = [
        "let myLet = 0"."var myVar = 0"."private let _myLet = 0"."class Abc { static let MyLet = 0 }"."let URL: NSURL? = nil"."let XMLString: String? = nil"."override var i = 0"."enum Foo { case myEnum }"."func isOperator(name: String) -> Bool"."func typeForKind(_ kind: SwiftDeclarationKind) -> String"."func == (lhs: SyntaxToken, rhs: SyntaxToken) -> Bool"."override func IsOperator(name: String) -> Bool"] // Error static is raisedlet triggeringExamples = [
        "Left the let down MyLet = 0"."Left the let down _myLet = 0"."private ↓let myLet_ = 0"."Left the let down myExtremelyVeryVeryVeryVeryVeryVeryLongLet = 0"."Left var myExtremelyVeryVeryVeryVeryVeryVeryLongVar = 0"."Private left the let down _myExtremelyVeryVeryVeryVeryVeryVeryLongLet = 0"."Left the let I = 0"."Left var id = 0"."private ↓let _i = 0".↓func IsOperator(name: String) -> Bool"."Enum Foo {case ↓MyEnum}"]}Copy the code

Rule 44: implicit_getter

Overriding the GET method is not recommended for read-only attributes only

Identification code Enable by default Whether automatic correction is supported type
implicit_getter To enable the no style

Code examples:

// Does not raise error // overwrite get andsetClass Foo {var Foo: Int {get {return3}set{_abc = newValue}}} // read-only class Foo {var Foo: Int {return 20 
  } 
}

class Foo {
  static var foo: Int {
     returnError class Foo {var Foo: Int {get {return 20 
    } 
  } 
}

class Foo {
  var foo: Int {
    get{
      return20}}}Copy the code

Rule 45: implicit_return

Implicit return closures are recommended; Foo.map ({$0 + 1})

Identification code Enable by default Whether automatic correction is supported type
implicit_return Is not enabled no style

Code examples:

// Foo. Map {$0 + 1 }
foo.map({ $0 + 1 })
foo.map { value inValue + 1} // Foo. Map {value not recommendedin
  return value + 1
}
foo.map {
  return $0+ 1}Copy the code

Rules: 46 implicitly_unwrapped_optional

Avoid the use of implicit resolution of optional types

Identification code Enable by default Whether automatic correction is supported type
implicitly_unwrapped_optional Is not enabled no idiomatic

Here is an official example:

    public static let description = RuleDescription(
        identifier: "implicitly_unwrapped_optional",
        name: "Implicitly Unwrapped Optional",
        description: "Implicitly unwrapped optionals should be avoided when possible.", kind:. Idiomatic, // Does not trigger warning nonTriggeringExamples: ["@IBOutlet private var label: UILabel!"."@IBOutlet var label: UILabel!"."@IBOutlet var label: [UILabel!] "."if ! boolean {}"."let int: Int? = 42"."let int: Int? = nil"Warning triggeringExamples: ["let label: UILabel!"."let IBOutlet: UILabel!"."let labels: [UILabel!] "."var ints: [Int!]  = [42, nil, 42]"."let label: IBOutlet!"."let int: Int! = 42"."let int: Int! = nil"."var int: Int! = 42"."let int: ImplicitlyUnwrappedOptional<Int>"."let collection: AnyCollection
      
       "
      !>."func foo(int: Int!) {}"])Copy the code

Rule 47: is_disjoint

When initializing a Set, set.isdisjoint () is recommended. Set. Intersection is not recommended

Identification code Enable by default Whether automatic correction is supported type
is_disjoint To enable the no idiomatic

Code examples:

// recommended syntax _ = Set(syntaxKinds). IsDisjoint (with: commentAndStringKindsSet)letisObjc = ! objcAttributes.isDisjoint(with: dictionary.enclosedSwiftAttributes)Copy the code

Rule 48: joined_default_parameter

Joined Method When the default separator is used, it is recommended to use the joined() method instead of the joined(separator: “”) method

Identification code Enable by default Whether automatic correction is supported type
joined_default_parameter Is not enabled yes idiomatic

Code examples:

// It is recommendedlet foo = bar.joined()
let foo = bar.joined(separator: ",")
letFoo = bar. Joined (separator: toto) // Not recommendedlet foo = bar.joined(separator: "")
let foo = bar.filter(toto).joined(separator: "")
Copy the code

Rule 49: large_tuple

Number of tuple members defined, more than two warnings

Identification code Enable by default Whether automatic correction is supported type
large_tuple To enable the no metrics

Code examples:

// Does not trigger warninglet foo: (Int, Int)
let foo: (start: Int, end: Int)
letFoo: (Int, (Int, String)) // Warning is emittedlet foo: (Int, Int, Int)
let foo: (start: Int, end: Int, value: String)
let foo: (Int, (Int, Int, Int))
Copy the code

Rules: 50 leading_whitespace

The file should not start with Spaces or line breaks, otherwise warning will be triggered

Identification code Enable by default Whether automatic correction is supported type
leading_whitespace To enable the yes style

Code examples:

Swift // SwiftLint // // Created by Langke on 17/1/12. // Copyright © 2017 Langke. All rights reserved. / / / / / will trigger warning / /... Swift // SwiftLint // // Created by Langke on 17/1/12. // Copyright © 2017 Langke. All Rights Reserved. / / / / / will trigger a warning...... Here is a blank line // // viewController.swift // SwiftLint // // Created by Langke on 17/1/12. // Copyright © 2017 Langke.all rights reserved. //Copy the code

Reference Documentation SwiftLint Official documentation SwiftLint describes rules in detail

Some explanations and examples may not be very perfect, I hope you can give me more guidance, and we will continue to update…….