Swiftlink Code Specification Property Description

Keywords: Attribute Swift less xcode

Detailed description of SwiftLint code specification attributes

  • Attribute 1: weak_delegate. Agents should be written as weak types (weak agents) to avoid circular references

For example:

/// 1.1 Compiled through
class Langke {
    var chenlong: NSObjectProtocol?
}

/// 1.2 Compiler passed, but triggered the weak_delegate warning of swiftlint because the variable name myDelegate has the delegate keyword, which is name abuse.
class Langke {
    var myDelegate: NSObjectProtocol?
}

/// 1.3 Compiled, no warning will be triggered, because the var keyword is preceded by weak
class Langke {
    weak var myDelegate: NSObjectProtocol?
}


/// 2.1 Compiler passes, but triggers weak_delegate warning because Delegate in scroll Delegate is placed at the end and is understood as a proxy
class Langke {
    var scrollDelegate: UIScrollViewDelegate?
}

/// 2.2 Compilation passes. Since variable names are understood as proxies, the keyword weak should be added in order to prevent circular references.
class Langke {
    weak var scrollDelegate: UIScrollViewDelegate?
}

/// Compilation passes without triggering a warning, because delegate is in front and is not understood as a proxy
class Langke {
    var delegateScroll: UIScrollViewDelegate?
}

To sum up, if you want to use the weak_delegate attribute in swiftlink, when the variable name you defined is understood as a proxy, you need to add the keyword weak to eliminate warning. The best way is not to take names randomly, for example, the name is also wrong: var delegate: String?, which triggers swiftlint warning!

  • Attribute 2: void_return. Return value is empty, we generally recommend "-> Void", rather than "-> ()", mainly for global variables / constants closures: let xingYun: () - > () = {}

For example:

/// Trigger void_return and attribute 46: redundant_void_return
func XingYun() -> () {
    print("Nebula is not strong enough to press sheep!")
}

// Trigger void_return
let xingYun: () -> ()

/// Void_return is not triggered, but the attribute 46: redundant_void_return is triggered
func XingYun() -> Void {
    print("Nebula is very powerful!")
}

// No trigger
let xingYun: () -> Void

Summarize, return to empty all unified keyword Void, do not use ()

  • Attribute 3: vertical_whitespace. Spatial lines in the vertical direction are limited to one line (except for comments).

For example:

/// No spaces, non Trigger Warning
override func viewDidLoad() {
    super.viewDidLoad()
    let aaa = 0
}   

/// There's a row of blanks, non Trigger Warning
override func viewDidLoad() {
    super.viewDidLoad()
    let aaa = 0
    ............................1
}

///>= Two lines, the warning will be triggered
override func viewDidLoad() {
    super.viewDidLoad()
    let aaa = 0
   .............................1
   .............................2
}

This is recommended for projects with a maximum number of vertical lines of up to 1, which ensures code fullness and readability.

  • Attribute 4: variable_name. Variable names should contain only character numeric characters, and should only begin with lowercase letters or should contain only uppercase letters. In addition, when the variable name is declared static (static) or immutable is immutable, it may start with a capital letter. Finally, the variable name should not be too long or too short (should be between 3 and 40 characters, otherwise it will trigger a warning!!! ) Note: Currently, variable names are only applicable to the parameters of methods written by themselves and the global constants or variables of class es written by themselves. They do not work in the methods that come with the system or in the methods written by themselves.

For example:

This example comes from official documents
   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"
    ],
    triggeringExamples: [
        "↓let MyLet = 0",
        "↓let _myLet = 0",    //I'm depressed here. Can't I name it this way?
        "private ↓let myLet_ = 0",
        "↓let myExtremelyVeryVeryVeryVeryVeryVeryLongLet = 0",
        "↓var myExtremelyVeryVeryVeryVeryVeryVeryLongVar = 0",
        "private ↓let _myExtremelyVeryVeryVeryVeryVeryVeryLongLet = 0",
        "↓let i = 0",
        "↓var id = 0",
        "private ↓let _i = 0"
    ]
  • Attribute 5: valid_ibinspectable. @ The use of IBInspectable in swiftlint requires attention. First, variables must be used. Second, specified types must be used. If the specified types are optional or implicit types, only the following types are officially supported at present:

    String, NSString, UIColor, NSColor, UIImage, NSImage.

For example:

/// Specify variable var, type String? And String!
@IBInspectable private var yyy: String?
@IBInspectable private var zzz: String!

/// If written in this way, the compilation can pass, but a warning is triggered because swiftlink does not support Int optional and implicit types for the time being:
@IBInspectable private var dddl: Int!
@IBInspectable private var eeel: Int?

/// If the specified type is not an optional type, it should be initialized. Otherwise, the system does not allow it, and the class where the error occurs is not initialized.
Yes:
@IBInspectable private var counts: Int = 0
 System error reporting:
@IBInspectable private var counts: Int 
  • Attribute 6: file_header. File header. Documents should have consistent annotations, mainly as shown in the following examples:

For example:

/// It does not trigger warning
 If I build a new project, in the ViewController.swift file, the starting comment should be:
//
//  ViewController.swift
//  SwiftLint
//
//  Created by langke on 17/1/17.
// Copyright 2017 langke. All rights reserved.
//

Change it to the following: ____________
//
// MyViewController.swift...... Because the filenames are different here from those outside, triggering warning (actually testing this property on swift 3.0 has no effect for the time being!)
//  SwiftLint
//
//  Created by langke on 17/1/17.
// Copyright 2017 langke. All rights reserved....... Official terminal said that if Copyright and Created are not aligned, warning will also be triggered!!!
//
  • Attribute 7: prohibited_super_call. Prohibited parent response. Some methods should not respond to the parent class.

For example:

/// It does not trigger warning
 class VC: UIViewController {
        override func loadView() {
          }
 }

 class NSView {
      func updateLayer() {
           self.method1()
      }
 }

/// It triggers warning
class VC: UIViewController {
      override func loadView() ↓{
              super.loadView()
      }
}

class VC: NSFileProviderExtension {
      override func providePlaceholder(at url: URL, completionHandler: @escaping (Error?) -> Void) ↓{
               self.method1()
                super.providePlaceholder(at:url, completionHandler: completionHandler)
      }
 }

class VC: NSView {
      override func updateLayer() ↓{
              self.method1()
              super.updateLayer()
              self.method2()
      }
 }
  • Attribute 8: colon. The colon attribute rule of swiftlink is simple, requiring ":" There must be no space next to the defined constants or variables, and there must be only one space between the specified type, one more or less. If used in Dictionary, there must be close to Key and only one space between Value. I think this rule should be recommended compulsorily. Because of its simplicity, there are no examples.
  • Attribute 9: comma. Comma rules, colons can make the code look less tired, headache, use as long as follow the "forward and backward step" on the line, which is also mandatory recommendation.
  • Attribute 10: trailing_newline. The description given by the official document is "Files should have single trailing newline". That is to say, there should be a new blank line at the end of the file (attributes, methods)("}), but here it is important to note that only should, not must, so this attribute is also an optional attribute. The official examples are as follows:

    /// An empty line will not trigger a warning
    nonTriggeringExamples: [
        "let a = 0\n"
    ],
    
    /// A warning will be triggered below.
    triggeringExamples: [
        "let a = 0",   /// Not empty, it triggers a warning (actually, I tried, it doesn't).
        "let a = 0\n\n"   /// Two empty lines trigger a warning (in fact, I tried to trigger a warning, but vertical_whitespace warning instead of trailing_newline)
    ],
    
    /// Here, it calls for an empty line of corrections. Although the code looks easy, it's too scattered if you define too many variables or constants. (It's worth saying that even if it's not empty, it won't trigger trailing_newline. As I said earlier, this attribute just says "should" rather than "must".)
    corrections: [
        "let a = 0": "let a = 0\n",
        "let b = 0\n\n": "let b = 0\n",
        "let c = 0\n\n\n\n": "let c = 0\n"
    ]
    

In this case, when does this attribute trigger back and where does the trigger actually occur? I tested it myself. This method triggers a trailing_newline warning at the end of the closure on the page of the current class, that is, a new line with a space behind "}", or no new line with a space. If >= 2, it triggers a trailing_newline warning, such as:

} Line 40
 Line 41 empty
 Line 42 blank line - ----> trigger warning

This property is an arbitrary property of swiftlink. If the style is particularly strict with the code, use it. The others have little effect.

  • Attribute 11: trailing_whitespace. Tail blank line, which is strongly not recommended. Look at the following examples:

For example:

/// The following example does not trigger a warning, but once one of the empty lines triggers a warning trailing_whitespace, which essentially conflicts with vertical_whitespace, which requires no more than one line between two lines of code, either no empty line or only one line, while trailing_whitespace requires no empty line!!
class ViewController: UIViewController {
override func viewDidLoad() {
    super.viewDidLoad()
    let a = 0
    let b = 1
    let c = 2
}
func chenlong() -> Void {
    let a = 0
    print(a)
}
}

This property is strongly not recommended, and no blank lines are allowed between codes, which will make the program less readable, so I hope to disable!!!

  • Attribute 12: line_length. Line character length property. This is strongly not recommended. The official rule is to give warning for more than 120 characters and report error directly for more than 200 characters!!! We are not writing low-level scripts, so we recommend that this method be disabled!!

  • Attribute 13: mark. Markup methods or attributes. This recommendation can be used to unify the format of method tags, which is helpful for review s to find a method or attribute more clearly. It's also very simple to use: "MARK" in front and "MARK:" in back.

  • Attribute 14: todo. TODO and FIXME should be avoided and replaced by "notaTODO and notaFIXME". In addition, unlike MARK tags, "notaTODO and notaFIXME" do not have a space requirement, but I recommend that if you use this todo attribute, try to write the same specification as MARK.

  • Attribute 15: trailing_comma. The trailing comma, which is strongly recommended, is mainly for the last element of the array and dictionary.

For example:

/// There's nothing wrong with writing an array like this, but the last element 3 is followed by a comma. "Although this does not cause errors, it makes the program less readable.
let ages = [1, 2, 3,]
let person = ["XingYun": 98, "JinGang": 128, "LangKe": 18,]

/// After using the trailing_comma rule of swiftlink, warning will be reported, so the correct writing should not add this "."
let ages = [1, 2, 3]
let person = ["XingYun": 98, "JinGang": 128, "LangKe": 18]
  • Attribute 16: trailing_semicolon. End semicolon is strongly recommended. Although there is no hard requirement in swift to add semicolons after assignment of variables or constants, in order to make code style more swift, try or never add ";".

  • Attribute 17: closing_brace. Closed braces, braces and brackets should not have any spaces in the middle, that is, "{}" and "()" can not have spaces, this property is recommended to use.

For example:

/// No problem.
({})
/// Problem
( {})
/// Problem
({} )
  • Attribute 18: closure_end_indentation. What does closure end indentation mean? It's the alignment of braces (usually methods) up and down, which makes the code look cleaner.

For example:

/// It is important to note that there is a space in front of "{" on the left side of braces, and if not, a closure_end_indentation warning will be triggered.
langke.beginFishing {.........
.............
}
  • Attribute 19: closure_spacing. Closure spaces, closure expressions should have a separate space in each bracket. Note that this refers to "should". I tested it myself and did not report warning in swift 3.0, so this is not a mandatory requirement, but this is recommended.

For example:

[].filter { content }
  • Attribute 20: closure_parameter_position. Closure parameter position, closure parameter should be in the same line as the left side of braces, recommended use.

For example:

/// number and {on the same line
let names = [1, 2, 3]
names.forEach { (number) in
    print(number)
}

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

/// This does not work, violating the closure_parameter_position rule, triggering warning
let names = [1, 2, 3]
names.forEach { 
    (number) in
    print(number)
}

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

Attribute 21: dynamic_inline. Dynamic Inline, avoid using dynamic and @inline (_always) together, otherwise report error

For example:

/// The Right Way
class LangKe {
dynamic func myFunction() {

}
}

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

    }
}

class LangKe {
    @inline(never) dynamic func myFunction() {

    }
}

/// As long as dynamic and @inline(_always) are used simultaneously, error s will be reported!!!
class LangKe {
    @inline(__always) public dynamic func myFunction() {

    }
}

I don't know why this attribute does this. Dynamics and @inline(_always) can't be used at the same time, but since it does so, it must have its reason, so this attribute is also recommended.

  • Attribute 22: unused_closure_parameter. For closure parameters that are not used, swiftlint suggests that closure parameters that are not used should be replaced by "". Recommended use.

For example:

/// It does not trigger warning
[1, 2].map { _ in 
    return 3
}

/// It triggers warning
[1, 2].map { number in
    return 3
}
  • Attribute 23: compiler_protocol_init. Compiler protocol initialization, attribute in swiftlink has an example, but I did not play any role in swift 3.0, so whether this attribute needs to be used is undetermined. However, after a careful look at the terminal s using swiftlint rules, no compiler_protocol_init attributes, perhaps new attributes, have yet been integrated into the new version?

For example, the official full explanation is as follows:

 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.",
    /// No warning will be triggered
    nonTriggeringExamples: [
        "let set: Set<Int> = [1, 2]\n",
        "let set = Set(array)\n"
    ],

    /// It triggers warning (actually I tested it in swift 3.0, and it doesn't trigger warning at all)
    triggeringExamples: [
        "let set = ↓Set(arrayLiteral: 1, 2)\n",
        "let set = ↓Set.init(arrayLiteral: 1, 2)\n"
    ]
)
  • Attribute 24: control_statement. Control statements, if, for, while, do statements should not write conditions in parentheses, and pay attention to the blanks of conditions.

For example:

      nonTriggeringExamples: [
        "if condition {\n",
        "if (a, b) == (0, 1) {\n",
        "if (a || b) && (c || d) {\n",
        "if (min...max).contains(value) {\n",
        "if renderGif(data) {\n",
        "renderGif(data)\n",
        "for item in collection {\n",
        "for (key, value) in dictionary {\n",
        "for (index, value) in enumerate(array) {\n",
        "for var index = 0; index < 42; index++ {\n",
        "guard condition else {\n",
        "while condition {\n",
        "} while condition {\n",
        "do { ; } while condition {\n",
        "switch foo {\n"
    ],
    triggeringExamples: [
        "↓if (condition) {\n",     /// There are "()", warning
        "↓if(condition) {\n",       /// There is no space between if and condition, and there is "()"
        "↓if ((a || b) && (c || d)) {\n",
        "↓if ((min...max).contains(value)) {\n",
        "↓for (item in collection) {\n",
        "↓for (var index = 0; index < 42; index++) {\n",
        "↓for(item in collection) {\n",
        "↓for(var index = 0; index < 42; index++) {\n",
        "↓guard (condition) else {\n",
        "↓while (condition) {\n",
        "↓while(condition) {\n",
        "} ↓while (condition) {\n",
        "} ↓while(condition) {\n",
        "do { ; } ↓while(condition) {\n",
        "do { ; } ↓while (condition) {\n",
        "↓switch (foo) {\n"
    ]

This property guarantees the simplicity of the code. Generally speaking, in the conditional sentence of swift, as far as possible without parentheses, write the condition directly, unless it is particularly necessary! In addition, pay attention to the blanks before and after the condition, generally there is a blank, this attribute is recommended to use.

  • Attribute 25: custom_rules. Custom rules. This property can create custom rules by providing regular expressions, optionally specifying the syntax type collocation, security, level, and what information to display. This property can not be applied at present as long as it is familiar with the use of regular expressions.

  • Attribute 26: cyclomatic_complexity. Cyclic complexity. The complexity of function body should be limited. This property mainly restricts the nesting of loop in conditional sentences and cyclic sentences. When too many cycles are nested, warning and error in swiftlink will be triggered. When 10 cycles are nested, warning will be reported. When 20 cycles are nested, error will be reported. This property is strongly recommended. Too many nests, poor readability!

For example:

// warning or error
func LangKe() -> Void {
    if true {
        if false {
            guard true else { return }

            if false {
                ...............Cyclic complexity
            }
        }
    }
}
  • Attribute 27: empty_count. Instead of checking whether count is zero, swiftlint says it prefers to check for "isEmpty".

For example:

/// swiftlint doesn't like to use this way
let number = "long"
if number.characters.count == 0 {
    print("Empty")
} else {
    print("Not empty")
}

/// swiftlint prefers this formal style
if number.isEmpty {
    print("Empty")
} else {
    print("Not empty")
}

This attribute is recommended. Although I did not trigger a warning when testing on swift 3.0, it is a good constraint to standardize the use of grammar by developers and more in line with the style of swift.

  • Attribute 28: statement_position. The position of the declarative sentence mainly refers to the addition of a space before the else and catch, which can not be larger than one space, otherwise the warning will be triggered.

For example:

    /// No space, trigger warning
    let number = "long"
    if number.isEmpty {
        print("Empty")
    }else {.............................Pay attention here.
        print("Not empty")
    }

    /// warning will also be triggered here, because else if newlines
    let number = "long"
    if number.isEmpty {
        print("Empty")
    }
    else if number.contains("long") {............................Pay attention here.
        print("Not empty")
    } else {
        print("s")
    }

    /// Correct Writing
    let number = "long"
    if number.isEmpty {
        print("Empty")
    } else {
        print("Not empty")
    }
  • Attribute 29: open_brace. At the time of declaration, the left bracket should have a space and be recommended on the same line.

For example:

/// trigger warning
let number = "long"
if number.isEmpty {
    print("Empty")
} else{............................Pay attention here.
    print("s")
}

/// nonTrigger warning
let number = "long"
if number.isEmpty {
    print("Empty")
} else {
    print("s")
}

Of course, if there are parentheses, there should be no spaces, such as ({}) -> which is the rule of closing_brand.

  • Attribute 30: empty_parameters. It is an empty parameter. swiftlint prefers "()->" to "Void->"

For example:

/// 01 does not trigger warning
let abc: () -> Void

func foo(completion: () -> Void) {

}

/// 02 Direct Error Reporting
let bcd: Void -> Void

func foo(completion: Void -> Void) {

}

/// If you look at swiftlint rules on the terminal, you should only report warning, but report error directly. Then the system prompts that "02" should be changed to:
let bcd: (Void) -> Void

func foo(completion: (Void) -> Void) {

}
  • Attribute 31: empty_parentheses_with_trailing_closure. Empty parentheses are used in trailing closures. When using trailing closures, empty parentheses should be avoided as much as possible and whether to use them is undetermined.

For example:

 /// Triggering warning
 [1, 2].map() { $0 + 1 }

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

 [1, 2].map() { number in\n number + 1 \n}

 [1, 2].map(  ) { number in\n number + 1 \n}

 /// It does not trigger warning
 [1, 2].map { $0 + 1 }

 [1, 2].map { $0 + 1 }

 [1, 2].map { number in\n number + 1 \n}

 [1, 2].map { number in\n number + 1 \n}
  • Attribute 32: file_length. File length. This attribute I tested on swift 3.0 did not work at all. The official content was:

    identifier: "file_length",
    name: "File Line Length",
    description: "Files should not span too many lines.",
    
    nonTriggeringExamples: [
        repeatElement("//\n", count: 400).joined()
    ],
    
    triggeringExamples: [
        repeatElement("//\n", count: 401).joined()
    ]
    
  • Attribute 33: force_cast. Mandatory conversion, mandatory conversion should be avoided, otherwise the error will be reported directly.

For example:

/// Correct Conversion
NSNumber() as? Int

/// Direct Error Reporting, No Mandatory Conversion
NSNumber() as! Int

This force_cast coercively converts attributes, but whether to use them remains to be discussed.

  • Attribute 34: force_try. Forced attempt is forbidden by swiftlink, otherwise error will be reported directly.

For example:

/// It's OK to write like this without triggering an error.
func myFunction() throws {

}
do {
    try myFunction()
} catch {

}

/// This triggers the error directly.
func myFunction() throws {

}
try! myFunction()
  • Attribute 35: function_body_length. Function body length, function body should not span too many lines, more than 40 lines to warning, more than 100 lines of direct error reporting. Recommended use.

  • Attribute 36: function_parameter_count. The number of function parameters, the number of function parameters (except init method) should be less, not too much, swiftlink specifies that the number of function parameters exceeds 5 to warning, and more than 8 to report errors directly. This attribute is recommended for use, because it is simple, there are no examples. Note: function_parameter_count: error does not change its warnings or errors. This property is not allowed to be modified, but can be disabled.

  • Attribute 37: imlicit_getter. Implicit getter method. Computed read-only attributes should avoid using get keywords, that is to say, if only for read-only, it can be returned directly, instead of writing get keywords, if it can be read and written, then it can be written.

For example:
/// Report warning
var foo: Int {
get{
return 20
}
}

    /// It should be written like this (directly)
    var foo: Int {
        return 20
    }

Summary: That is to say, if only get is a key word, you can not write get. If there is set besides get, you can write get. Simplify it: read-only computing attribute omits get, read-write attribute omits get, of course, this is only for computing read-only attribute.

  • Attribute 38: legacy_cggeometry_functions. Legacy C G geometric functions, when obtaining the width, height, minimum X, maximum X value of a view, etc., swiftlink recommends using the standard grammar of swift, try not to use the legacy version from Objective-C, as far as possible grammatical swifting.

For example:

/// This is not recommended.
CGRectGetWidth(someView.frame)

/// The following form is recommended
rect.width
rect.height
rect.minX
rect.midX
rect...................

/// In swift 3.0, Xcode 8.1, I made the following attempt: CGRectGetMaxX has been replaced by property CGRect.maxX
let myLabel = UILabel(frame: CGRect(x: CGRectGetMaxX(myView.frame), y: 22, width: 33, height: 44))

/// According to the ** system ** prompt message changed as follows
let myLabel = UILabel(frame: CGRect(x: myView.frame.maxX, y: 22, width: 33, height: 44))

Summary: swiftlink has already attached this attribute to the system's native API, and many CG geometric functions brought by OC have been discarded. This attribute is strongly recommended for use.

  • Attribute 39: legacy_constant. Legacy version constants, like attribute 38 (legacy_cggeometry_functions), are as segregated, explicit and specific as possible, and do not use OC's legacy global constants.

For example:

/// Normative writing does not trigger warning
CGPoint.zero

/// Irregular writing triggers warning
CGPointZero
CGRectZero

It is recommended that such a grammar be used, and swift 3.0 has begun to enforce the use of this specification's point grammar.

  • Attribute 40: legacy_constructor. Legacy version constructor, swiftlint requires the system to bring its own constructor, using swift grammar, do not use OC version of the constructor.

For example:

/// swift grammar, swift 3.0 has been mandatory, so although swiftlint does not customize this rule, the system will also mandatory use
CGPoint(x: 10, y: 20)

/// Error constructor grammar
CGPointMake(10, 20)
  • Attribute 41: legacy_nsgeometry_functions. ns class geometric functions, like the previous several properties, use swift point grammar functions, not the previous version.

For example:

//Correct
view.width/height/minX

//Error
NSWidth(view.frame)
  • Attribute 42: operator_usage_whitespace. Operators use rules, and there should be spaces on both sides of the operator. For example, "+""-"?"?

For example:

let sum = 1 + 2
let mutiplier = 2 * 3
let devide = 10 /2
  • Attribute 43: overridden_super_call. Override the parent method, strongly recommended.

For example:

/// Correct Writing
override func viewWillAppear(_ animated: Bool) {

    /// Pay attention to overwriting parent methods
    super.viewWillAppear(animated)
}

* Attribute 44: private_outlet. Private output, the IBOutlet property should be private, in order to avoid exposing UIKits to higher levels, official: "IBOutlets should be private to avoid leaking UIKits to higher layers."

For example:

/// Swiftlint suggests adding a private after the IBOutlet attribute to indicate private when using it, but I tested it on swift 3.0, and although swiftlint was used, it didn't work at all.

// swiftlint recommends that you do not write as follows
class LangKe {
     @IBOutlet var label: UILabel?
}

/// swiftlint recommends this
class LangKe {
     @IBOutlet private var label: UILabel?
}
  • Attribute 45: redundant_string_enum_value. Redundant string enumeration values. When defining string enumeration, do not make the enumeration value equal to the enumeration member name

For example:

// warning 1
enum Numbers: String {
    case one = "one"
    case two
}

enum Numbers: String {
    case one 
    case two = "two"
}

enum Numbers: String {
    case one = "one"
    case two = "two"
}

Of course, as long as there is a case whose member name and enumeration value are not equal, there is no warning, for example:

enum Numbers: String {
    case one = "ONE"
    case two = "two"
}
  • Attribute 46: redundant_void_return. The redundant return value is empty, and when the function is declared, the return value is empty. You can define constants or variables.

For example:

/// This property requires this to be written, and the return value is null ellipsis
func XingYun() {
    print("press")
}

/// This property requires that you don't write like this, otherwise warning will occur (but I did not trigger warning on swift 3.0)
func XingYun() -> Void {
    print("press")
}

Note: In attribute 2, void_return prefers "-> Void" to "-> ()", which does not mean that using - > Void is good. I think it is better to omit, so this attribute is recommended.
  • Attribute 47: return_arrow_whitespace. Back to the arrow space, swiftlink recommends that the return arrow and return type should be separated by the space, that is, there is a space between "->" and type.

For example:

/// report warning
func XingYun() ->Int {
    print("Press cattle")
    return 22
}

/// Do not report warning - --> Recommended use
func XingYun() -> Int {
    print("Press cattle")
    return 22
}

/// Swiftlink does not object to the line change between "->" and "type" and does not report warning - --> but does not recommend its use.
func XingYun() -> 
Int {
    print("Press cattle")
    return 22
}
  • Attribute 48: type_name. Type names, which should contain only alphanumeric characters, should begin with capital letters and be 3-40 characters in length. There's nothing to say about this attribute. It's highly recommended.

  • Attribute 49: syntactic_sugar. Grammatical sugar, swiftlint recommends shorthand grammatical sugar, such as [Int] instead of Array, strongly recommended.

For example:

    /// Triggering warning
    let myArray: Array<Int> = [1, 2, 3]
    print(myArray)

    /// Writing correctly will not trigger warning
    let myArray: [Int] = [1, 2, 3]
    print(myArray)
  • Attribute 50: switch_case_on_newline. In switch grammar, case should always be on a new line. Look at the examples.

For example:

    /// swiftlink indicates that warning will be triggered
    switch type {
    case .value1: print("1")...................On the same line
    case .value2: print("2")...................On the same line
    default: print("3")...................On the same line
    }

    /// It does not trigger warning
    switch type {
    case .value1:
        print("1")
    case .value2:
        print("2")
    default:
        print("3")
    }

In summary, it requires that in the switch statement, case requires line breaks. This attribute is strongly recommended.

  • Attribute 51: shorthand_operator. Shorthand operator, what is the shorthand operator? In swiftlint, it is the simple operator we often use, such as: +=, -=, *=, /= and so on. In swiftlink, short operators are recommended when doing some assignment operations.

For example:

    /// Not recommended (warning or error is not triggered on swift 3.0)
    var value = 4
    value = value / 2
    print(value)

    /// Recommended use
    var value = 4
    value /= 2
    print(value)
  • Attribute 52: sorted_imports. Classification/orderly import. This property is somewhat strange, requiring imported classes to be imported sequentially when imported. In addition, swiftlint rules are not used temporarily on terminal s. Look directly at the official examples:

For example:

    identifier: "sorted_imports",
    name: "Sorted Imports",
    description: "Imports should be sorted.",


    nonTriggeringExamples: [
        "import AAA\nimport BBB\nimport CCC\nimport DDD"
    ],


    triggeringExamples: [
        "import AAA\nimport ZZZ\nimport ↓BBB\nimport CCC"
    ]

This attribute is not recommended. It is not necessary to import in order when importing. Generally speaking, you will not import too many classes in the project, especially in the swift language.

  • Attribute 53: number_separator. Digital dividing line. When in a large number of decimals, the underline should be used as the microdecimal dividing line. Recommended use.

For example:

    /// Recommended use of this form
    let xxx = 1_000_000_000.000_1
    print(xxx)

    /// It is not recommended to use this form (there is no warning on swift 3.0, that is to say, this attribute does not work for the time being)
    let xxx = 1000000000.0001
    print(xxx)
  • Attribute 54: nimble_operator. Agile operators. Compared with free matching functions, agile operators are preferred, such as: >=, ==, <=, < and so on.

For example:

/// It triggers warning
(person.voice).toNot(equal("Hello world"))     // Man's voice is not equal to "Hello world"
10.to(beGreaterThan(5))                     // 10 to 5.
99.to(beLessThan(100))                  // 99 to 100.

// Changed to the following
(person.voice) != "Hello world"         // Man's voice is not equal to "Hello world"
10 > 5                  // 10 to 5.
99 < 100                // 99 to 100.
  • Attribute 55: nesting. Nested. Types are nested at most one-level structure, and functional statements are nested at most five-level structure.

For example:

/// no warning
func langke() {
    func xingyun() {
        func caicai() {
            func xiaohui() {
                func jingang() {

                }
            }
        }
    }
 }

 /// trigger warning
 func langke() {
    func xingyun() {
        func caicai() {
            func xiaohui() {
                func jingang() {

                    //Start triggering warnings
                    func beginTriggerWarning() {

                    }
                }
            }
        }
    }
 }
  • Attribute 56: redundant_optional_initialization. Redundant optional initialization. When optional variables are initialized to nil, they are redundant. description: Initializing an optional variable with nil is redundant.

For example:

/// Trigger warning (actually not on swift 3.0)
var myVar: Int? = nil
var myVar: Optional<Int> = nil
var myVar: Int?=nil
var myVar: Optional<Int>=nil

/// Correct Writing
var myVar: Int? 
var myVar: Optional<Int> 
var myVar: Int?
var myVar: Optional<Int>

This property can be used, although it is not available on terminal for the time being, it should be integrated into the corresponding swiftlink environment in the future.

  • Attribute 57: lead_whitespace. There should be no spaces or line breaks at the beginning of the file, otherwise warning will be triggered.

For example:

/// It does not trigger warning
//
//  ViewController.swift
//  SwiftLint
//
//  Created by langke on 17/1/12.
//  Copyright 2017 langke. All rights reserved.
//

/// It triggers warning
 //There's a space here.
//  ViewController.swift
//  SwiftLint
//
//  Created by langke on 17/1/12.
//  Copyright 2017 langke. All rights reserved.
//

/// It triggers warning
......................................Here is an empty line.
//
//  ViewController.swift
//  SwiftLint
//
//  Created by langke on 17/1/12.
//  Copyright 2017 langke. All rights reserved.
//
  • Attribute 58: vertical_parameter_alignment. Vertical alignment of parameters. When the function parameters have multiple lines, the function parameters should be aligned in the vertical direction (left aligned when the parameters change lines). This property is currently not available on terminal using swiftlint rules.

For example:

   nonTriggeringExamples: [
      func validateFunction(_ file: File, kind: SwiftDeclarationKind,
                            dictionary: [String: SourceKitRepresentable]) { }

      func validateFunction(_ file: File, kind: SwiftDeclarationKind,
                            dictionary: [String: SourceKitRepresentable]) -> [StyleViolation]


      func validateFunction(_ file: File, kind: SwiftDeclarationKind,
                            dictionary: [String: SourceKitRepresentable])
                            -> [StyleViolation]

      func validateFunction(
         _ file: File, kind: SwiftDeclarationKind,
         dictionary: [String: SourceKitRepresentable]) -> [StyleViolation]

      func validateFunction(\n" +
         _ file: File, kind: SwiftDeclarationKind,\n" +
         dictionary: [String: SourceKitRepresentable]
      ) -> [StyleViolation]\n",
    ]


    triggeringExamples: [
        func validateFunction(_ file: File, kind: SwiftDeclarationKind,
                          dictionary: [String: SourceKitRepresentable]) { }
        func validateFunction(_ file: File, kind: SwiftDeclarationKind,
                               dictionary: [String: SourceKitRepresentable]) { }
        func validateFunction(_ file: File,
                          kind: SwiftDeclarationKind,
                          dictionary: [String: SourceKitRepresentable]) { }
    ]
  • Attribute 59: conditional_returns_on_newline. The conditional return statement should be on the new line. When conditional return occurs, it should be returned in a new line, not in the same line. This attribute is strongly recommended.

For example:

/// Writing not recommended by swiftlink will trigger warning (but testing on swift 3.0 will not trigger any warning)
if true { return }
guard true else { return }

/// Writing recommended by swiftlint
if true {
    return
}

guard true else {
    return 
}
  • Attribute 60: force_unwrapping. Forced unpacking/unpacking. We know that when a type is an optional type, when we get the value, we need to force unpacking (also known as implicit unpacking). Usually we add a "!" after a variable or the required constants, types, etc. However, swiftlint suggests that forced unpacking should be avoided or warning will be given.

For example:

/// warning will be triggered
navigationController!.pushViewController(myViewController, animated: true)

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

return cell!

/// It does not trigger warning
navigationController?.pushViewController(myViewController, animated: true)
  • Attribute 61: explicit_init. Explicit initialization. Explicit initialization should be avoided.

For example:

/// Explicit initialization triggers warning (but I actually tested on swift 3.0 and found no trigger warning!!!).
[88].flatMap{ String↓.init($0) }
UITableView.init()

/// Correct Writing
[88].flatMap{ String($0) }
UITableView()
  • Attribute 62: missing_docs. The missing annotation, official explanation: "Public declarations should be documented." Public declarations should be annotated / marked. In general, when declaring functions, annotations of functions with public keywords can only be annotated with "//" and "/*/", and functions without public keywords can only be annotated with "//" and "/*/". This property should be disabled, no need!!!

For example:

Not trigger warning

// public, documented using /// docs
/// docs
public func langke() {}

// public, documented using /** docs */
/** docs */
public func langke() {}

// internal (implicit), undocumented
func langke() {}

// internal (explicit) / private, undocumented
internal/private func langke() {}


1,Protocol members are marked and annotated by files, but inherited members are not required.
/// docs
public protocol A {
    /// docs
    var b: Int { get }
}

/// docs
public struct C: A {
    public let b: Int
}

2,Locally defined parent class members are marked by files, but child class members are not required.
/// docs
public class A {
    /// docs
    public func b() {}
}

/// docs
public class B: A {
    override public func b() {}
}

3,Externally defined parent class members are marked by files, But subclass members do not need to
import Foundation
/// docs
public class B: NSObject {
    // no docs
    override public var description: String { fatalError() }
}

</br>
</br>

//It will trigger warning (actually not at swift 3.0 right now!)
// public , undocumented
public func langke() {}

// public , undocumented
// regular comment
public func a() {}

// public, undocumented
/* regular comment */
public func a() {}


  // protocol member and inherited member are both undocumented
  /// docs
  public protocol A {
        // no docs
        var b: Int { get } 
  }
  /// docs
  public struct C: A {

        public let b: Int
  }
  • Attribute 63: valid_docs. Valid documents. The document declaration should be valid. This attribute conflicts with attribute 62 and is duplicated. There is a problem with official document writing. In addition, warning does not occur on swift 3.0. For the time being, this property is disabled!!! Later, it will be added after the official perfection.

  • Attribute 64: type_body_length. Type body length. Type body length should not span too many lines, more than 200 lines for warning and more than 350 lines for error. Usually in brackets or brackets, such as defining an enum or struct.

For example:

class langke {
    Here are 201 lines, warning!!!
}
  • Attribute 65: redundant_nil_coalescing. The redundant is the empty union operator. The null union operator is used to determine whether the left is null or not, and the null operator accompanied by nil is redundant on the right.

For example:

/// Triggering warning
 var myVar: Int? = nil
 myVar↓ ?? nil

 var myVar: Int? = nil
 myVar↓??nil

 //It does not trigger warning
 var myVar: Int?
 myVar ?? 0

 var myVar: Int? = nil
 let langke = myVar
  • Attribute 66: object_literal. Object literals, swiftlint means object literals are preferred to image and color initialization. Because swift initialization can use expressions, pictures, colors, etc., which is not in line with some of the idioms of the project. Currently, swiftlint rules is not used in terminal to view this property. Naturally, testing on swift 3.0 has not worked at all. But this attribute is recommended.

For example:

/// Official example, non-triggering warning
"let image = #imageLiteral(resourceName: \"image.jpg\")",
"let color = #colorLiteral(red: 0.9607843161, green: 0.7058823705, blue: 0.200000003, alpha: 1)",
"let image = UIImage(named: aVariable)",
"let image = UIImage(named: \"interpolated \\(variable)\")",
"let color = UIColor(red: value, green: value, blue: value, alpha: 1)",
"let image = NSImage(named: aVariable)",
"let image = NSImage(named: \"interpolated \\(variable)\")",
"let color = NSColor(red: value, green: value, blue: value, alpha: 1)"
  • Attribute 67: private_unit_test. Private unit testing. Unit tests marked as private are not run by the test tool XCTest, that is to say, unit tests marked as private are static skipped.

For example:

 private ↓class FooTest: XCTestCase { ...............Inheritance to test case classes XCTestCase, Marked as private,So trigger warning
     func test1() {}
     internal func test2() {}
     public func test3() {}
     private func test4() {}.......In addition, notice here, since the above will not pass, then obviously it will not pass here, and it will not go this way at all. func
 }  

 internal class FooTest: XCTestCase { ......Begin to pass the test because it is not marked as private
     func test1() {}
     internal func test2() {}
     public func test3() {}
     private ↓func test4() {}................No, because it's marked as ____________ private
 }

 public class FooTest: XCTestCase { ..........adopt
     func test1() {}
     internal func test2() {}
     public func test3() {}
     private ↓func test4() {}.................No, because it's marked as private
 }

 class FooTest: XCTestCase { ..........adopt
     func test1() {}
     internal func test2() {}
     public func test3() {}
     private ↓func test4() {}.................No, because it's marked as private
 }
  • Attribute 68: frist_where. Looking directly at the official explanations and examples below, this property is not tested.

For example:

    description: "Prefer using `.first(where:)` over `.filter { }.first` in collections.",

    nonTriggeringExamples: [
        "kinds.filter(excludingKinds.contains).isEmpty && kinds.first == .identifier\n",
        "myList.first(where: { $0 % 2 == 0 })\n",
        "matchPattern(pattern).filter { $0.first == .identifier }\n"
    ],

    triggeringExamples: [
        "↓myList.filter { $0 % 2 == 0 }.first\n",
        "↓myList.filter({ $0 % 2 == 0 }).first\n",
        "↓myList.map { $0 + 1 }.filter({ $0 % 2 == 0 }).first\n",
        "↓myList.map { $0 + 1 }.filter({ $0 % 2 == 0 }).first?.something()\n",
        "↓myList.filter(someFunction).first\n"
    ]
  • Attribute 69: operator_whitespace. Spatial/blank operators. When defining a space operator, there should be a single line of space operators on both sides of the defined name or type. Recommended use.

For example:

// Trigger warning
class Something: Equatable {
var text: String?

// There should be a space between "==" and "(lhs: Something, rhs: Something)"
static func ==(lhs: Something, rhs: Something) -> Bool {
    return lhs.text == rhs.text
}

}
  • Attribute 70: overridden_super_call. Some override methods should always call the parent class

For example:

 /// This triggers a warning.
 class VCd: UIViewController {
     override func viewWillAppear(_ animated: Bool) {
        //No parent class was invoked

     }
 }

 /// No warning will be triggered
  class VCd: UIViewController {
     override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

     }
  }






Continuous updates are ongoing ___________ ..

Posted by jawaidpk on Fri, 29 Mar 2019 09:15:30 -0700