Remove redundant identifier in optional binding guard

This product is not supported for your selected Datadog site. ().
이 페이지는 아직 영어로 제공되지 않습니다. 번역 작업 중입니다.
현재 번역 프로젝트에 대한 질문이나 피드백이 있으신 경우 언제든지 연락주시기 바랍니다.

Metadata

ID: swift-code-style/guard-let-shorthand

Language: Unknown

Severity: Warning

Category: Code Style

Description

This rule identifies and flags redundant identifiers in optional binding within guard statements, such as guard let name = name else { ... }. In Swift, when the identifier on the left side of the binding is the same as the optional being unwrapped, you can omit the explicit assignment and write guard let name else { ... } instead. This simplification improves code readability by reducing unnecessary repetition.

To comply with this rule, simply omit the explicit assignment when unwrapping an optional with the same identifier, using guard let variable else { ... } rather than guard let variable = variable else { ... }. Always prefer this concise form unless you need to bind to a different variable name or perform type casting.

Notes

Non-Compliant Code Examples

guard let name = name else {
    // ...
}

guard let self = self else {
    // ...
}
    
guard interactionEnabled,
   let userTapLocation = userTapLocation else {
    // ...
}

guard let user = user, 
   var device = device else {
    // ...
}

Compliant Code Examples

guard let name else {
    // ...
}

guard let name = user?.name else {
    // ...
}
    
guard let user = user as? User else {
    // ...
}
 
guard var user = currentUser() else {
    // ...
}
https://static.datadoghq.com/static/images/logos/github_avatar.svg https://static.datadoghq.com/static/images/logos/vscode_avatar.svg jetbrains

원활한 통합. Datadog Code Security를 경험해 보세요