开发者

Check if string is not nil or not empty using Swift 5

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)
            .fontWeig开发者_如何学Pythonht(.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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜