如何阻止SwiftLint --fix --format修改闭包格式,保留Xcode风格?
SwiftLint格式化闭包与Xcode风格不一致的解决办法
我在使用SwiftLint 0.50.03版本的Swift项目中,运行swiftlint lint --fix --format命令后,闭包的缩进格式被修改,和Xcode用Cmd + I格式化后的风格不一致。
场景对比
Xcode格式化后的闭包代码:
ASStoreManager.shared.makeRegisterAPIRequest(withEmail: emailInputView.formattedText, withPassword: passwordInputView.formattedText, withFullName: fullNameInputView.formattedText, completion: { errors in ASLoaderUtils.shared.hide() if let errors = errors { ASAlertUtils.shared.presentAlert(withErrors: errors) } else { ASFirebaseManager.logEvent(withEventName: ASFirebaseConstants.Events.User.signUp, withParameters: ASFirebaseManager.getUserParameters()) let viewController = ASConfirmationViewController(withConfirmationViewControllerType: .Register) viewController.callbacks.buttonDidTap = { ASStoreManager.shared.makeLogIn() } let navigationController = viewController.embedToNavigationController() navigationController.modalPresentationStyle = .fullScreen self.present(navigationController, animated: true) } })
SwiftLint格式化后的闭包代码:
ASStoreManager.shared.makeRegisterAPIRequest(withEmail: emailInputView.formattedText, withPassword: passwordInputView.formattedText, withFullName: fullNameInputView.formattedText, completion: { errors in ASLoaderUtils.shared.hide() if let errors = errors { ASAlertUtils.shared.presentAlert(withErrors: errors) } else { ASFirebaseManager.logEvent(withEventName: ASFirebaseConstants.Events.User.signUp, withParameters: ASFirebaseManager.getUserParameters()) let viewController = ASConfirmationViewController(withConfirmationViewControllerType: .Register) viewController.callbacks.buttonDidTap = { ASStoreManager.shared.makeLogIn() } let navigationController = viewController.embedToNavigationController() navigationController.modalPresentationStyle = .fullScreen self.present(navigationController, animated: true) } })
我尝试过在SwiftLint配置中禁用或启用closure_body_length、closure_end_indentation等规则,但都无法阻止SwiftLint修改闭包格式,请问怎么让SwiftLint停止修改闭包格式,保留Xcode的格式化风格?
解决方法
1. 移除SwiftLint的格式化参数
SwiftLint的--format参数会调用自身内置的格式化工具,其逻辑和Xcode原生格式化不一致。如果只需要SwiftLint做代码规则检查和非格式类问题修复,可以去掉该参数,仅运行:
swiftlint lint --fix
2. 配置SwiftLint对齐Xcode缩进规则
如果必须保留--format参数,可在项目根目录的.swiftlint.yml配置文件中调整规则:
- 禁用SwiftLint的闭包缩进格式化规则:
disabled_rules: - closure_indentation - 确保缩进宽度和Xcode一致(Xcode默认4空格):
opt_in_rules: - indentation_width indentation_width: 4
3. 让SwiftLint与Xcode格式化工具联动
通过自定义脚本,先让SwiftLint处理代码规则问题,再调用Xcode内置工具统一格式,避免冲突。示例脚本:
# 用SwiftLint修复非格式类问题 swiftlint lint --fix # 调用Xcode格式化代码(替换为你的项目/Target名称) xcodebuild -project YourProject.xcodeproj -target YourTarget -quiet format -fix
内容的提问来源于stack exchange,提问作者poPaTheGuru
相关产品推荐
相关产品推荐

