Reputation: 2381
In Objective-C:
if (!myImageView) {
NSLog(@"hdhd");
}
else {
//DO SOMETHING
}
But in Swift:
if (!myImageView) {
println("somethin")
}
else {
println("somethin")
}
This code is giving me the error:
Could not find an overload for '!' that accepts the supplied arguments'
myImageView
is class variable UIImageView
.
What should I do?
Upvotes: 0
Views: 523
Reputation: 15400
If your variable is of type UIImageView
then it cannot ever be nil.
However if you want your code to be equivalent to your Objective-C code, change the variable type to UIImageView?
(an optional type) and replace:
if (!myImageView) {
with:
if (myImageView == nil) {
Upvotes: 1
Reputation: 62052
Usually, the best way to deal with checking variables for nil
in Swift is going to be with the if let
or if var
syntax.
if let imageView = self.imageView {
// self.imageView is not nil
// we can access it through imageView
} else {
// self.imageView is nil
}
But for this to work (or for comparison against nil
with either == nil
or != nil
), self.imageView
must be an optional (implicitly unwrapped or otherwise).
Non-optionals can not be nil
, and therefore the compiler will not let you compare them against nil
. They'll never be nil
.
So if if let imageView = self.imageView
or self.imageView != nil
or self.imageView == nil
are giving you errors, it's almost certainly because self.imageView
is not an optional.
Upvotes: 2