1

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.
2
  • if let website = item.website, !item.website.isEmpty { should be if let website = item.website, !website.isEmpty {. Then you won't get the warning. Commented Dec 7, 2022 at 4:00
  • possible duplicate of Check string for nil & empty Commented Dec 7, 2022 at 6:15

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

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 If website isn't optional then your whole question becomes irrelevant.
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?
If the value coming from the database can be nil, then the variable you are storing it in should be an optional.
Thanks for the explanation @vacawama, I will update the variable to handle optional.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.