I am trying to delete a row from my Data Source and the following line of code:
if let tv = tableView {
causes the following error:
Initializer for conditional binding must have Optional type, not UITableView
Here is the full code:
// Override to support editing the table view.
func tableView(tableView: UITableView, commitEditingStyle editingStyle:UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
if let tv = tableView {
myData.removeAtIndex(indexPath.row)
tv.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
How should I correct the following?
if let tv = tableView {
This question is related to
ios
swift
optional-binding
What it is telling you is - the 2nd guard let
or the if let check
is not happening on an Optional Int or Optional String. You already have a non-optional value, so guarding or if-letting is not needed anymore
Well, it'd still be convenient (syntactically) if we could declare usual values inside the if's condition. So, here's a trick: you can make the compiler think there is an assignment of Optional.some(T)
to a value like so:
if let i = "abc".firstIndex(of: "a"),
let i_int = .some(i.utf16Offset(in: "abc")),
i_int < 1 {
// Code
}
condition binding must have optinal type which mean that you can only bind optional values in if let statement
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
if let tv = tableView as UITableView? {
}
}
}
This will work fine but make sure when you use if let it must have optinal type "?"
In a case where you are using a custom cell type, say ArticleCell, you might get an error that says :
Initializer for conditional binding must have Optional type, not 'ArticleCell'
You will get this error if your line of code looks something like this:
if let cell = tableView.dequeReusableCell(withIdentifier: "ArticleCell",for indexPath: indexPath) as! ArticleCell
You can fix this error by doing the following :
if let cell = tableView.dequeReusableCell(withIdentifier: "ArticleCell",for indexPath: indexPath) as ArticleCell?
If you check the above, you will see that the latter is using optional casting for a cell of type ArticleCell.
for my specific problem I had to replace
if let count = 1
{
// do something ...
}
With
let count = 1
if(count > 0)
{
// do something ...
}
Same applies for guard statements. The same error message lead me to this post and answer (thanks @nhgrif).
The code: Print the last name of the person only if the middle name is less than four characters.
func greetByMiddleName(name: (first: String, middle: String?, last: String?)) {
guard let Name = name.last where name.middle?.characters.count < 4 else {
print("Hi there)")
return
}
print("Hey \(Name)!")
}
Until I declared last as an optional parameter I was seeing the same error.
Source: Stackoverflow.com