【问题标题】:How to fix 'Line Length Violation: Line should be 120 characters or less' - SwiftLint如何修复“行长违规:行应为 120 个字符或更少” - SwiftLint
【发布时间】:2018-08-04 13:49:39
【问题描述】:

如何解决线路长度违规问题?

由于行长违规而不允许的警报消息的相关部分:message: NSLocalizedString("\nYou will be requested to Use %@ to Sign In. %@ doesn't share any information about you. The permission is required to post your Live Video.", ⚠ 行应为 120 个字符或更少:当前为 208 个字符 (line_length)

【问题讨论】:

  • 这看起来像一条 SwiftLint 消息。
  • @rmaddy 是的,但不知道如何解决它
  • 好吧,缩短行或禁用警告(在github.com/realm/SwiftLint/blob/master/… 明确解释)
  • @matt 同样的方式,这个问题似乎很难理解,但马丁确实回答了它

标签: swift swiftlint


【解决方案1】:

让行更短:

message: NSLocalizedString(
    ["\nYou will be requested to Use %@ to Sign In. ",
    "%@ doesn't share any information about you. The ",
    "permission is required to post your Live Video."].joined()
)

或者更好,使用 vacawama 的多线解决方案:

let message = 
    """

    You will be requested to Use %@ to Sign In. \
    %@ doesn't share any information about you. \
    The permission is required to post your Live Video.
    """

这是一个通用的解决方案,但并不适合 NSLocalizedString,因为它会破坏扫描本地化字符串(如 genstrings)的工具。

您的另一个解决方案是通过在之前的行上添加禁用来关闭该行的警告:

// swiftlint:disable:next line_length

有关禁用 swiftlint 规则的完整详细信息,请参阅 Disable rules in code

【讨论】:

  • 如果用反斜杠结束行,则不会引入换行符。
  • @vacawama 哇……我不知道。太棒了。
  • 禁用 linting 规则从来都不是一个好的解决方案。如果你开始这样做,那么一开始就没有任何意义。根本问题是本地化工具希望您使用默认消息作为本地化键。将整个消息放入代码中是没有意义的,一个简单的字符串代码,例如"sign_in_info' 也可以。
  • 我不同意禁用 linting 规则从来都不是一个好的解决方案。如果这是真的,它们将是编译器错误。我们将警告与 linting 分开的事实是有意的。 Linting 是故意过分严格的。即使在 Go 中,诸如未能使用变量之类的良性事情都是编译时错误,仍然存在有时可以忽略的 linter(govet)。缩短本地化密钥与使用自动化工具之间的正确选择没有统一的答案。说“linter 禁止使用 Apple 的本地化工具”是愚蠢的一贯做法。
  • (我这么说是作为“一种真正的 Swift 风格”的长期倡导者,这样 clang-format 将强制以一种方式布局 Swift 代码。即使我有我的方式,有时会忽略 linter。openradar.appspot.com/radar?id=5886836526284800)
【解决方案2】:

在这种情况下,只需使用 ignores_interpolated_strings 更新您的 line_length 规则,如下所示:

line_length:
  warning: 120
  ignores_function_declarations: true
  ignores_comments: true
  ignores_interpolated_strings: true
  ignores_urls: true

并确保您使用的是最新版本的swiftlint(几周前还是added

【讨论】:

  • 不忽略 cmets。
  • 它不起作用 :( 它尝试将相同的内容放入 .yml 文件中,但仍然出现相同的警告,目前仅以下内容有效 line_length: 200 我不想要所有行跨度>
  • 警告不会通过 ignores_interpolated_strings 这件事
  • 还是不行
【解决方案3】:

在 .swiftlint.yml 规则文件中添加的这行代码对我有用

# implicitly 
line_length: 110

【讨论】:

    猜你喜欢
    • 2021-09-06
    • 2019-07-21
    • 2020-06-10
    • 2021-02-26
    • 2021-02-09
    • 2019-11-24
    • 1970-01-01
    • 2020-07-04
    • 2020-12-04
    相关资源
    最近更新 更多