I'm coming from a Java/Android background where we use NULL. Now I am doing Swift/iOS and I am confused as to what Swift's nil means.
Can I use it like NULL in Java? Does it act the exact same way or is there something different about its usage?
You can think of 'null' and 'nil' the same. Whether the language includes optionals is a separate concern.
Objective-C, has 'nil', but does not have in-built optionals while Swift does. Similarly, Java has 'null', but not have implicit optionals, while several JVM languages such as Kotlin, Scala and Ceylon do, and did so before Swift.  
Here's an article that compares about null, nil and optionals in Kotlin, Scala and Swift: http://codemonkeyism.com/comparing-optionals-and-null-in-swift-scala-ceylon-and-kotlin/
Incidentally, for Android development you may want to investigate Kotlin and the associated Anko library from Jetbrains.
Swift does not currently support a null coalescing operator.
Swift nil explanation
nil means "no value". Non-optional variables cannot be assigned nil even if they're classes, so it's explicitly not a null pointer and not similar to one.
I can recommend you to read more about optionals in Swift.
Disclosure: I don't know a whole terrible lot about Java, so my answer is coming from a C++/Objective-C/Swift perspective.
Matt Thompson of NSHipster has a great post about it and how it relates to Objective-C vs C. You can find it here.
The answer basically boils down to this: you should consider it the same.
0 is how you represent nothing for a primitive value
NULL is how you represent nothing for literal for C pointers
nil is how you represent nothing for literal Objective-C/Swift objects
Related
While checking a parser of a JSON in swift, I found the following code:
description = "desc" <~~ json
I suppose that it is similar to use the following:
description = json["desc"]
Is it correct? if no, what does this operator mean?
Thanks
You are right. But it would be wrong to assume that's what it is set out to do in Swift.
I think the parser that was being used was Gloss, and it seems that they have written an operator overload specifically to mean description = json["desc"] (and or or some other stuff under the hood to make the parsing easier) . The operator does not have a meaning per se in Swift. But it's invented by the framework to do the parsing.
You can read about operator overloading here
EDIT
I always have incorrectly used the terms operator overloading and defining custom operator interchangeably. Operator Overloading is extending the implementation of the existing operators which is different than defining your own custom operators. Thank you SO MUCH for pointing this out, #Giacomo Alzetta!
Is it normal to get an extra "Optional("")" on the strings i am fetching in Core Data?
Here is the code
bowtie.name = "My bow tie"
bowtie.lastWorn = NSDate()
And this is what i am getting in the xcode output log.
Name: Optional("My bow tie"), Worn: Optional(2015-11-08 14:23:11 +0000)
Is there a way to get rid of the Optional("") thing?
Every time you force unwrap an Optional (using !) a kitten dies.
There are several safe ways of unwrapping an Optional such as using if let or flatMap (even though it's not a real flatMap).
In several cases you can use Optional Chaining so you don't have to deal with Optionals before you actually have to. The null coalescing operator (??) is also pretty useful.
This SO answer is extremely helpful, you should definitely check it out.
If you want to fully understand the concept of Optionals take a look at the docs.
In that specific case, though, I'd recommend using something like let fetchedName = bowtie.name ?? "" (or any other fallback string that makes sense for your problem).
When you force unwrap and for some bizarre reason the value is nil the app will crash. Nobody likes crashes, right?
I was wondering the difference of using and not using type annotations(var a: Int = 1 vs var a = 1) in Swift, so I read Apple's The Swift Programming Language.
However, it only says:
You can provide a type annotation when you declare a constant or variable, to be clear about the kind of values the constant or variable can store.
and
It is rare that you need to write type annotations in practice. If you provide an initial value for a constant or variable at the point that it is defined, Swift can almost always infer the type to be used for that constant or variable
It doesn't mention the pros and cons.
It's obviously that using type annotations makes code clear and self-explanatory, whereas not using it is easier to write the code.
Nonetheless, I'd like to know if there are any other reasons(for example, from the perspective of performance or compiler) that I should or should not use type annotations in general.
It is entirely syntactic so as long as you give the compiler enough information to infer the correct type the affect and performance at run time is exactly the same.
Edit: missed your reference to the compiler - I cannot see it having any significant impact on compile times either as it needs to evaluate your assignment expression and check type compatibility anyway.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
Can I create a normal variable in Swift (I mean a non-optional) and assign a nil value to it or later during the app lifecycle, let it be nil?
It confuses me, since it's a little strange compared to traditionally strong programming languages, like Java and C#.
No, that's not possible by design. This excerpt from the documentation explains why:
The concept of optionals doesn’t exist in C or Objective-C. The nearest thing in Objective-C is the ability to return nil from a method that would otherwise return an object, with nil meaning “the absence of a valid object.” However, this only works for objects—it doesn’t work for structures, basic C types, or enumeration values. For these types, Objective-C methods typically return a special value (such as NSNotFound) to indicate the absence of a value. This approach assumes that the method’s caller knows there is a special value to test against and remembers to check for it. Swift’s optionals let you indicate the absence of a value for any type at all, without the need for special constants.
You are describing optionals as a bad thing, whereas is one of the features I appreciate more in the language, because it prevents most of the null pointer exception bugs.
Another advantage is that when a function can return a non-value (nil for reference types in objective C, -1 for integers, etc.), you don't have to choose a value from the spectrum of possible values that a variable of a certain type can have. Not mentioning that it's a convention that both the caller and the function/method must follow.
Last, if you are using too many question and exclamation marks in your code, then you should think about whether or not optionals are really appropriate for the problem (thanks #David for the hint), or taking advantage of optional binding more frequently in all cases where optionals are really needed.
Suggested reading: Optionals
Addendum
Hint: I've frequently seen uses of optionals in cases where a variable is declared, but cannot be initialized contextually. Non optional mutable variables are not required to be declared and initialized in the same line - deferred initialization is allowed, provided that the variable is not used before its initialization. For example:
var x: Int // Variable declared here
for var counter = 0; counter < 10; ++counter {
println(counter)
}
var array = [1, 2, 3]
// ... more lines of code NOT using the x variable
x = 5 // Variable initialized here
print(x)
Hopefully this feature will let you remove several optionals from your code...
Can I create a normal variable in SWIFT (I mean a non Optional) and assign a nil value to it or later during the app lifecycle, let it be nil.
No.
This is easily testable in the playground:
var str = "Hello, playground"
str = nil
The second line will get this error:
Type 'String' does not conform to protocol 'NilLiteralConvertible'
You might want to read more about Swift Literal Convertibles and see an example of how to use it.
You are right, you cannot set a non-optional to nil, although this seems like a burden at first, you gain a lot of safety and readability by giving away a tiny bit of flexibility. Once you get used to it, you will appreciate it more and more.
I have a problem understanding co-existence of "null" and Option in F#. In a book I have read that null value is not a proper value in F# because this way F# eliminates the excessive null checking. But it still allows null-initialized references in F#. In other words, you can have null values but you don't have the weapons to defend yourself with. Why not completely replace nulls with Options. Is it because of compatibility issues with .NET libraries or languages that it's still there? If yes can you give an example that shows why it can't be replaced by Option?
F# avoids the use of null when possible, but it lives in the .NET eco-system, so it cannot avoid it completely. In a perfect world, there would be no null values, but you just sometimes need them.
For example, you may need to call .NET method with null as an argument and you may need to check whether a result of .NET method call was null.
The way F# deals with this is:
Null is used when working with types that come from .NET (When you have a value or argument of type declared in .NET, you can use null as a value of that type; you can test if it equals null)
Option is needed when working with F# types, because values of types declared in F# cannot be null (And compiler prohibits using null as a value of these types).
In F# programming, you'll probably use option when working with .NET types as well (if you have control over how their values are created). You'll just never create null value and then use option to have a guarantee that you'll always handle missing values correctly.
This is really the only option. If you wanted to view all types as options implicitly when accessing .NET API, pretty much every method would look like:
option<Control> GetNextChild(option<Form> form, option<Control> current);
...programming with API like this would be quite painful.