I'm trying to build a collection view with pagination (showing cells as previews) and found this tutorial. I'm getting the error from Xcode and guessing this must be due to an update to Xcode (since the tutorial seemed to have worked for a lot of people). Would love a hint on how to fix this:
Downcast from '[UICollectionViewLayoutAttributes]?' to
'[UICollectionViewLayoutAttributes]' only unwraps optionals; did you
mean to use '!'?
You probably did something like this (someOptionalAttributes being of type [UICollectionViewLayoutAttributes]?):
someOptionalAttributes as! [UICollectionViewLayoutAttributes]
However, because someOptionalAttributes is just the optional version of [UICollectionViewLayoutAttributes], you do not need a force downcast, you just need to unwrap it:
someOptionalAttributes!
Force downcasting is only necessary if casting to an entirely new type (usually subclass).
So, yes, you did mean to use ! as said in the error. If you want to be safe, you could use a number of different optional unwrapping techniques.
Related
Having problems iterating through an optional enumerated type. Looking for general guidance if anyone has any and will post any code if needed.
It all stems from this
#Published var movielist: Movie?
but I'm really confused on how to handle this error.
(vm.movielist?.results ?? []).enumerated()
This way, if vm.movielist is nil, then an empty collection gets used instead.
(this is the first "Fix" solution that Xcode gives, although sometimes it gets the syntax a little bit funny when it tries to fix things automatically that are in a chain like this)
This question already has answers here:
What is an optional value in Swift?
(15 answers)
Closed 5 years ago.
So I've recently been learning Swift (3.1), and I've had problems with understanding the purpose/practical usage of optionals.
I've researched several sites, and all they talk about is how to use them, not why or when they are used (Sort of why, but not in a way that seems applicable to me). My citations are at the end.
I understand about how its either nil or a value, and how you need to unwrap it's possible value with !, as well as how to create auto-unwrapping optionals.
My main question is just, what are the practical uses of optionals? Apple's Swift handbook said that optionals are the central point of most of Swift's most powerful features, so I feel like it is a concept very worthwhile to fully understand. I fully understand how to write them, I just can't grasp why or when you would use them.
Citations:
https://www.tutorialspoint.com/swift/swift_optionals.htm
http://blog.teamtreehouse.com/understanding-optionals-swift
Thank you for your time.
As per my understanding :
Swift is a safe bound checking language , so it implements it using variable checking whether they are nil or assigned value.
Optionals can be used when you don't know for sure before hand that we would have a value in a specific variable throughout the program.
So if you defined a Text Field & assigned its text to a variable. Maybe user just keeps it blank & you binded that text field's data to a variable.
On runtime it would be empty , for reasons to avoid crash you could define an optional.
In the program when you would access optional value you have to make sure that the variable is present using "if let optional" or explicitly unwrapping the optionals. Explicitly unwrapping optionals are bad move & only should be done when you're sure there is a value present in that optional variable.
Swift uses optionals everywhere.
Disclosure : I'm still new to Swift & this would be first answer. Maybe my answer isn't well put to Stack Overflow's standards.
I've only seen people using let to unwrap optionals.
I was wondering if it is a good practice and I could just as well use var, or is there something more to it?
What are the pros and cons of using let versus var?
It like usual;
let is for a constant (you will not be able to modify the value).
The good practice is to always use let when you can (when you don't need to modify the value). It is for optimization purpose and for clarity of the code.
As mentioned before, you should always use let when you can, as it allows compiler do some fancy stuff and thus makes your program run faster.
There is technically nothing wrong with using var, though.
For further reading, please check out this article:
http://www.touch-code-magazine.com/swift-optionals-use-let/
I was reading up on how to program in Swift, and the concept of optionals bugged me a little bit. Not really in terms of why to use optionals, that makes sense, but more so as to in what case would you not want to use optionals. From what I understand, an optional just allows an object to be set to nil, so why would you not want that feature? Isn't setting an object to nil the way you tell ARC to release an object? And don't most of the functions in Foundation and Cocoa return optionals? So outside of having to type an extra character each time to refer to an object, is there any good reason NOT to use an optional in place of a regular type?
There are tons of reasons to NOT use optional. The main reason: You want to express that a value MUST be available. For example, when you open a file, you want the file name to be a string, not an optional string. Using nil as filename simply makes no sense.
I will consider two main use cases: Function arguments and function return values.
For function arguments, the following holds: If the argument needs to be provided, option should not be used. If handing in nothing is okay and a valid (documented!) input, then hand in an optional.
For function return values returning no optional is especially nice: You promise the caller that he will receive an object, not either an object or nothing. When you do not return an optional, the caller knows that he may use the value right away instead of checking for null first.
For example, consider a factory method. Such method should always return an object, so why should you use optional here? There are a lot of examples like this.
Actually, most APIs should rather use non-optionals instead of optionals. Most of the time, simply passing/receiving possibly nothing is just not what you want. There are rather few cases where nothing is an option.
Each case where optional is used must be thoroughly documented: In which circumstances will a method return nothing? When is it okay to hand nothing to a method and what will the consequences be? A lot of documentation overhead.
Then there is also conciseness: If you use an API that uses optional all over the place, your code will be cluttered with null-checks. Of course, if every use of optional is intentional, then these checks are fine and necessary. However, if the API only uses optional because its author was lazy and was simply using optional all over the place, then the checks are unnecessary and pure boilerplate.
But beware!
My answer may sound as if the concept of optionals is quite crappy. The opposite is true! By having a concept like optionals, the programmer is able to declare whether handing in/returning nothing is okay. The caller of a function is always aware of that and the compiler enforces safety. Compare that to plain old C: You could not declare whether a pointer could be null. You could add documentation comments that state whether it may be null, but such comments were not enforced by the compiler. If the caller forgot to check a return value for null, you received a segfault. With optionals you can be sure that noone dereferences a null pointer anymore.
So in conclusion, a null-safe type system is one of the major advances in modern programming languages.
The original idea of optionals (which existed long before Swift) is to force programmer to check value for nil before using it — or to prevent outside code from passing nil where it is not allowed. A huge part of crashes in software, maybe even most of them, happens at address 0x00000000 (or with NullPointerException, or alike) precisely because it is way too easy to forget about nil-pointer scenario. (In 2009, Tony Hoare apologized for inventing null pointers).
Not using optionals is as valid and widespread use case as using them: when the value absolutely can not be missing, there should be non-optional type; when it can, there should be an optional.
But currently, the existing frameworks are written in Obj-C without optionals in mind, so automatically generated bridges between Swift and Obj-C just have to take and return optionals, because it is impossible to automatically deeply analyze each method and figure out which arguments and return values should be optionals or not. I'm sure over time Apple will manually fix every case where they got it wrong; right now you should not use those frameworks as an example, because they are definitely not a good one. (For good examples, you could check a popular functional language like Haskell which had optionals since the beginning).
Is it possible to concoct a compile time assert in Swift like static_assert in C++? Maybe some way to exploit type constraints on generics to force a compiler break?
This has been accepted into Swift as of version 4.2, here is the Swift evolution for the proposal.
If you're talking about a general assert, where the app will crash if a given condition fails, just use: assert(condition,message)
For example: assert(2 == 3,"failing because 2 does not equal 3")
This is possible in Swift. However, I should note that Apple's design mantra is that an app should never crash, but instead should handle all its errors in a "sophisticated" fashion.