0

So I want to utilize something that has the best performance, but also check for both nil and also not empty on strings.

Example: If the string is not nil, but also not empty, show showLinkButton.

So I was able to use this code:

if let website = item.website, !item.website.isEmpty {
    showLinkButton
}

Where I have a @ViewBuilder such as this:

@ViewBuilder private var showLinkButton: some View {
    Button(action: {
        self.isBrowsingWebsite = true
    }, label: {
        Image(systemName: "link")
            .resizable()
            .scaledToFit()
            .frame(height: 14)
            .fontWeight(.bold)
            .padding(5)
    })
    .foregroundColor(.secondary)
    .background(
        RoundedRectangle(cornerRadius: 5, style: .continuous)
            .fill(Color(.systemGray6))
    )
    .sheet(isPresented: $isBrowsingWebsite) {
        SafariViewWrapper(url: URL(string: item.website)!)
    }
}

Problem:
The problem is that I'm not really doing anything with let website, so I am getting the following errors:

Immutable value 'website' was never used; consider replacing with '_' or removing it && Replace 'let website' with '_'.

Questions:

  • If I utilize if _ = item.website, !item.website.isEmpty, will this hurt performance? Is there a better way to do it?
  • Since I will have multiple if statements, would if _ = ... have negative side effects being called 5+ times in the same View.
theMap
  • 43
  • 5
  • `if let website = item.website, !item.website.isEmpty {` should be `if let website = item.website, !website.isEmpty {`. Then you won't get the warning. – HangarRash Dec 07 '22 at 04:00
  • possible duplicate of [Check string for nil & empty](https://stackoverflow.com/questions/29381994/check-string-for-nil-empty) – Qazi Ammar Dec 07 '22 at 06:15

1 Answers1

2

Use optional chaining to call isEmpty and compare explicitly to false:

if item.website?.isEmpty == false {
    print("not nil and not empty")
}

Note:

If you want to check if a value is nil, just compare it to nil. Don't use if let unless you want to use the unwrapped value.

vacawama
  • 150,663
  • 30
  • 266
  • 294
  • I am getting this error `Cannot use optional chaining on non-optional value of type 'String'`. Could I utilize it without the optional `?` - Nvm, I updated the `var website: String?`. – theMap Dec 07 '22 at 04:01
  • 1
    @theMap If `website` isn't optional then your whole question becomes irrelevant. – HangarRash Dec 07 '22 at 04:03
  • A value can't be `nil` unless it is an *optional*. Why are you trying to test if it is `nil` if it isn't *optional*? – vacawama Dec 07 '22 at 04:04
  • If the value coming from the database can be `nil`, then the variable you are storing it in should be an *optional*. – vacawama Dec 07 '22 at 04:07
  • Thanks for the explanation @vacawama, I will update the variable to handle optional. – theMap Dec 07 '22 at 04:08