You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修复SwiftLint的「行长度违规:行应≤120字符」问题

解决SwiftLint行长度违规(NSLocalizedString超长场景)

嘿,我之前也碰到过一模一样的情况——用NSLocalizedString写长文本触发了SwiftLint的line_length警告,给你几个实用的解决办法,按需选就行:

方案1:把长字符串拆成多行代码(不改变最终文本内容)

Swift支持字符串拼接或者多行字符串语法,把代码拆成每行不超过120字符的片段就可以避开警告。如果不想让最终文本里出现换行,推荐用这两种写法:

字符串拼接方式

message: NSLocalizedString(
    "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.",
    comment: "Third-party sign-in permission prompt"
)

多行字符串(无换行版)

用"""包裹字符串,每行末尾加\可以取消自动换行,保证最终文本和原来完全一致:

message: NSLocalizedString("""
    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.
    """, comment: "Third-party sign-in permission prompt"
)

方案2:临时忽略该行的SwiftLint规则

如果不想修改字符串结构,可以直接在违规代码行上方加注释,让SwiftLint跳过这一行的line_length检查:

// swiftlint:disable:next line_length
message: NSLocalizedString("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.", comment: "Third-party sign-in permission prompt")

这种方式适合临时快速解决,不过不推荐长期大量使用,毕竟规则存在是有规范意义的。

方案3:将文本移到本地化.strings文件中(推荐长期方案)

其实这才是NSLocalizedString的规范用法——把实际的长文本放到Localizable.strings文件里,代码里只用简短的key,既解决行长度问题,也方便后续多语言维护:

代码中使用key

message: NSLocalizedString("SignIn_Permission_Prompt", comment: "Prompt for requesting third-party sign-in permission")

Localizable.strings中添加文本

"SignIn_Permission_Prompt" = "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.";

这样代码里只有简短的key,完全不会触发行长度警告,而且后续要修改文本或者添加其他语言时,直接修改.strings文件即可,不用动业务代码。

个人更推荐第三种方案,从工程规范和长期维护的角度来看都是最优解~

内容的提问来源于stack exchange,提问作者Yatko

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 09:51:57