Returning an implicitly unwrapped optional - swift

I'm writing a program in Swift which has various functions which should always return values, but in some cases cannot, and so the program crashes and alerts the user of the error. To accomplish this, I am using implicitly unwrapped Optionals as return values for my functions, so that error cases can just return nil (even though that code will never be reached). It looks something like this:
func giveMeAThing() -> Thing! {
if !possibleErrorCase() {
var thing = createAThingForSure()
return thing
}
else {
crashAndBurn()
return nil
}
}
Writing this, it feels a bit hacky, so my question is whether or not this is a good use of implicitly unwrapped Optionals in Swift. Is there a better way to structure my code that will avoid this?

It may be that the piece of the puzzle you are missing is #noreturn. If you declare a function as #noreturn, the compiler abandons any complaints if you don't fulfill the surrounding contract. Thus you can call such a method and not return any value, and the compiler will not complain because it knows we are going to die anyway. For example, fatalError and abort are declared this way.
Thus, the following is legal:
func f() -> String {
fatalError("oooooops")
}
That compiles even though we fail to fulfill the contract of returning a value, because #noreturn (in the declaration of fatalError) tears up the contract and flushes the pieces down the toilet.
Another possible way of approaching the same issue is to use assert. This crashes and burns for you if a condition is not met. So, in your example:
func giveMeAThing() -> Thing {
assert(!possibleErrorCase(), "gaaaaah!") // crash and burn if error case
return createAThingForSure()
}
The downside is that by default all asserts succeed in a shipping app. But it's great during development, and after all your shipping app should not be crashing and burning anyway.

I'd rather write this as
func giveMeAThing() -> Thing! {
if possibleErrorCase() {
crashAndBurn() // I assume this will not return anyhow
}
return createAThingForSure()
}
but that's likely just a question of taste.

You don't need an implicitly unwrapped optional since you don't expect the second case to return any value.
As commenters noted, use fatalError in the fail case.

Related

Swift short syntax of execution

I am looking for the way to write short syntax.
For instance. In JS, PHP and etc.
var a = 1 ;
function Foo ()-> void {}
a && Foo() ;
if a exists, run Foo.
a and Foo itself already mean exist or not, the syntax is away better looks....
However, in Swift, the typing checking is kinda of tough.
var a = 1 ;
func Foo ()-> Foid {} ;
a && Foo();
will generate neither are Bool returning error.
a != nil && Foo() ;
this can resolve and variable condition, but what if the better bypass for the function condition? I just dont want to write something like
if( a != nil ) { Foo() } ;
Yet what is the better syntax for Not Exist?
if ( !a ) or !a //is easy and better looks...
I found not similar thing in swift...
if( a == nil ) // will throws error when its not Optional Typing.
guard var b = xxx else {} // simply for Exist and very long syntax.
Thank you for your advice!
As mentioned by other contributors, Swift emphasizes readability and thus, explicit syntax. It would be sacrilege for the Swift standard library to support Python-style truth value testing.
That being said, Swift’s extensibility allows us to implement such functionality ourselves—if we really want to.
prefix func !<T>(value: T) -> Bool {
switch T.self {
case is Bool.Type:
return value as! Bool
default:
guard Double(String(describing: value)) != 0
else { return false }
return true
}
}
prefix func !<T>(value: T?) -> Bool {
guard let unwrappedValue = value
else { return false }
return !unwrappedValue
}
var a = 1
func foo() -> Void { }
!a && !foo()
Or even define our own custom operator:
prefix operator ✋
prefix func ✋<T>(value: T) -> Bool {
/// Same body as the previous example.
}
prefix func ✋<T>(value: T?) -> Bool {
guard let unwrappedValue = value
else { return false }
return ✋unwrappedValue
}
var a = 1
func foo() -> Void { }
✋a && ✋foo()
The expectations you've developed from dynamic languages like PHP and JS (and Ruby, Python for that matter) are almost universally inapplicable to static languages like Swift.
Swift is a statically compiled language. If you reference a variable that doesn't exist, it's not legal Swift code, and the compiler will fail your build. Given that, the question of "how do I check if a variable is undefined?" is completely moot in Swift. If you have a successfully compiling program that references a variable a, then a exists. There's absolutely no reason for a check, and so a mechanism for it doesn't even exist.
Static vs Dynamic typing
Static type systems are like mathematical proof systems. They produce rigerous proofs that certain aspects of your program are valid. This has trade-offs. The rigidity buys you many guarantees. For example, you'll never have a valid Swift program where you accidentally pass an Int where a Bool is expected. The static type system makes that class of error literally impossible, so it's not something you have to remember to check for yourself.
On the other hand, many truths are easier to intuit than to prove. Thus, there's great utility in scripting and dynamic languages, because they don't demand the rigorous proofs of your claims that static languages require. On the down side, their type systems "do" much less. For example, JS happily lets you reference an undefined variable. To remedy this, JS provides a way for you to do a run-time check to see whether a variable is defined or not. But this isn't a problem Swift has, so the "solution" is absent.
When static typing is too hard
Swift actually takes a middle ground position. If you find yourself with a statement that's obviously true, but hard to prove to the compiler, various "escape hatches" exist that allow you to leave the safety of the type system, and go into dynamic land. For example, if you look at an IBOutlet, and see that it's connected to an element in a storyboard, you can intuitively be sure that the IBOutlet is not nil. But that's not something you can prove to the compiler, and hence when you see implicitly unwrapped optionals being used for IBOutlets.
Implicitly unwrapped optionals are one such "escape hatch". The Any type is another, as is unsafeBitcast(_:to:), withoutActuallyEscaping(_:), as!, try!, etc.
Swift takes type safety very seriously. Unlike C or JS we can not use anything that doesn't resolve to Bool value type in If statement in Swift. So there won't be a short hand for that(at-least that I know of). Regarding below code
if( a == nil ) // will throws error when its not Optional Typing.
Swift doesn't allow you to set nil to non optional types. So there is no need to check for nil. By the way both Obj-C and Swift use verbose syntax, we need to get use to that.
In this case you are trying to force Swift to work in a way that you are used to with other languages like JavaScript or PHP, as you say in your comment. There are a few reasons why your code won't compile, but it mainly falls on the fact that Swift doesn't do the same truthy and falsy stuff JS does.
var a = 1
if a {
print("won't compile")
}
//'Int' is not convertible to 'Bool'
In Swift it's better to use an actual Bool value if that's what it's supposed to be, or if it's truly supposed to be an Int you're just going to have to check the value
var a = true
if a {
print("this compiles")
}
or
var a = 1
if a > 0 {
print("this compiles too")
}
Swift really isn't meant to be as loose as JS, so you should just embrace that and take advantage of the safety and readability.
Here is one way most similar to what you designed.
You may have to set the type of a to Int?:
var a: Int? = 1
func foo ()-> Void {}
a.map{_ in foo()}

How can you mark a method that it is fatal, like `fatalError`?

We have a special logging function that represents a particular type of crash, and as such, internally it calls fatalError. However, unlike fatalError, when we use it in a guard statement, it still complains we haven't exited the scope of the guard.
I checked the source code and fatalError returns -> Never so I tried that, but that didn't work either. I also didn't see any attributes applied to it that may be telling the compiler 'this is the end of the road'.
So is it possible to have your own fatalError-like method?
func myFatalError(memberName:String = #function) -> Never {
let message = "Failed in \(memberName)"
NSLog(message)
fatalError(message)
}
As pointed out by others, the issue was something on my machine specifically. The following (returning 'Never') works as expected.
func myFatalError() -> Never {
print("Doing something fatal")
}

Can I make self.entity a non optional for certian functions in a GKComponent using swift?

I'm using the GameplayKit entity component system to develop a game.
I have a number of GKComponent. Most of the instance functions require that self.entity is not nil, but it is an optional, as a component may be initialised before being attached to an entity.
If I "do things properly", I understand I should use guard (or if) to check that self.entity is not nil, for each function where I require it. This adds a chunk of extra code for each function, and in addition a function may require the entity has specific components to function.
Problem statement:
For some functions in a GKComponent, I want to specify that the function requires self.entity is not nil, and has some specific components, without needing a number of guard or if statements which bulks up my code.
Things I've tried:
I tried creating an extension to GKComponent.
The extension contains a function which throws an error if the entity is nil, returns true if it is not nil.
import Foundation
import GameplayKit
extension GKComponent {
enum ComponentExtensionError: Error {
case hasNoEntity
}
func requiresEntity() throws -> Bool {
if (self.entity != nil) {
return true
} else {
throw ComponentExtensionError.hasNoEntity
}
}
}
GKComponent function:
func setTileWalls () {
try? self.requiresEntity()
# Some stuff
}
This compiles, but doesn't solve my problem, as I still have to access the entity as self.entity?.somefunc().
I figured now I know that self.entity is not nil, I could proceed to set it as unwrapped...
func setTileWalls () {
try? self.requiresEntity()
self.entity = self.entity!
# Some stuff
}
But alas, you cannot SET self.entity.
I considered I could in stead modify the extension to return the entity, and then do something like...
func stTileWalls () {
guard let entity = self.requiresEntity() else { throw }
}
but then I'd need to modify each functions code to use entity rather than self.entity. I don't feel like this is optimal solution, but maybe an acceptable one.
My ideal solution would be to be able to call a function which checks that self has an entity, and some components, making them non optional for the scope, and throwing an error if any are nil.
Why? I'm frustrated by entity and any component always being optional (when I know it shouldn't be). If I understand correctly, "doing things properly" requires that I guard and throw (or return maybe?). Syntactically I feel it looks ugly and I feel like I'm missing something in terms of fixing this in an elegent way with Swift.
There is no easy solution to solve this issue if you want a safe solution that requires less boilerplate code than unwrapping an optional.
Throwing an error instead of returning nil is definitely a bad idea, since handling an error requires even more boilerplate code than safely unwrapping an optional.
You cannot override existing variables types, so you cannot make GKComponent.entity non-optional either.
Use guard statements for optional binding, that way you can minimise the boilerplate code for unwrapping the value.

What is the advantage of force unwrapping an optional? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
If a variable is an Optional what is the advantage of force unwrapping it.
class Button: UIButton {
var title: UILabel? = nil
required init?(coder aDecoder: NSCoder) {
fatalError()
}
override init(frame: CGRect) {
super.init(frame: frame)
}
func addTitle(text: String) {
title = UILabel(frame: CGRect())
self.addSubview(title!)
}
}
let a: Button = Button(frame: CGRect())
a.addTitle("Hello World")
// Case 1
a.title?.text = "Goodbye"
// Case 2
a.title!.text = "Hello World"
Question
In Case 1 I know its safer but is there any performance improvements or reason to use Case 2?
So, if we know that Case 1 is more safe why should we ever use Case 2?
Performance-wise there might be a very to very very small no difference between forced and optional binding/chaining, as the optional version might have an extra if somewhere.
But nonetheless when talking about performance issues, the performance bottlenecks come from other parts of the code, like non-improved loops, lots of accumulation NSNotification's sent in a short amount of time, unnecessary redraws of the UI, etc.
So it's best to stay on the safer side and use optional binding/casting/chaining and focus on the parts of the code that adds actual performance penalties. Even if at the time you write the code the value is guaranteed to be non-nil, in the future in might be that the conditions will change and you'll suddenly end up with crashes that you didn't expect they'll occur.
Swift has made it very easy to deal with optionals, without writing a lot of boilerplate code, you should take advantage of those features.
As per the comment, your example isn't actually valid. Putting that aside: force unwrapping means "I work only with a concrete value; I want to fail immediately if I don't have one". So it's often preferable to proceeding through that section of code with a nil value and then having some other problem sometime later once the causal nexus has been substantially eroded.
So: it allows you to be explicit about who owns responsibility for guaranteeing that a value is present.
Good (or at least defensible) reasons to use implicitly unwrapped Optionals, or to force unwrap an Optional using !:
#IBOutlets: These are normally implicitly unwrapped for a couple of reasons. You don't want to have to manually unwrap them every time you access them. But more importantly, if your outlets aren't hooked up right, you want to know immediately.
Other instances where you make a conscious decision that you want the app to crash if a value is nil. For example, if you are instantiating a view controller from a storyboard and it is required to be a particular subclass of UIViewController called MyViewController in order for your app to function at all, you might force cast it using return vc as! MyViewController. That way you discover right away that something is off.
Honestly, that's it, as far as I can tell. Just my own approach, but I reserve the ! for declaring #IBOutlets. Otherwise, 99.999% of the time I unwrap with if let or guard, or ? in an an optional chaining situation. There are other ways to know that the value is nil. If the optional fails to unwrap, print a message to the console telling you that it failed. To me, a short descriptive message is easier to debug than a crash and an unexpectedly found nil while unwrapping an optional value error. If I want the program to fail, I can still use fatalError with a descriptive message:
guard let x = someOptional else { fatalError("someOptional is nil in awakeFromNib.") }
By reserving ! for #IBOutlets, every time I get one of those unexpectedly found nil while unwrapping an optional value errors I know exactly where to look to find the source of my problem. I look at my #IBOutlet connections in interface builder. Sticking to that policy, and using other tools to identify other values that are nil when they shouldn't be, works for me.
Some alternatives (avoid force unwrapping !). Try these out using an non-nil value of a as well as when a contains nil.
var a: String? = nil
a = "Hello World"
// Case 1 : nil coalescing operator
print(a ?? "a has value nil, let's not unwrap it!")
// Case 2 : if-let clause
if let a = a {
print(a)
}
else {
print("a has value nil, let's not unwrap it!")
}
// Case 3 : guard-let-else clause
func foo(a: String?) {
guard let a = a else {
print("a has value nil, let's not unwrap it!")
return
}
print(a)
}
foo(a)

Failing a Swift initializer without setting stored property

I'm writing an application Bluetooth-controlled keynote remote. This will be using AppleScript to control Keynote based on interactions with the CoreBluetooth framework.
Consider this class, which requires the use of an optional OSALanguage initializer.
class KeynoteController {
let applescriptLanguage: OSALanguage
init?() {
if let applescriptLanguage = OSALanguage(forName: "AppleScript") {
self.applescriptLanguage = applescriptLanguage
} else {
return nil // Compile error on this line
}
}
}
In this example, I want to fail initializing my KeynoteController if there's no OSALanguage named "AppleScript" (admittedly unlikely, but good design). However, I can't return from my initializer until all stored properties are populated.
I could make applescriptLanguage an optional, but since it's non optional and constant if initialization succeeds, this seems like a hack.
What's the correct way to design this?
The problem seems to come from trying to make applescriptLanguage a non-optional. The compiler wants it to be assigned a value, even if the object is failing initialization.
Fix it by making it optional property (implicitly unwrapped because it should never actually be nil after initialization).
let applescriptLanguage: OSALanguage!
This seems like a compiler error to me, but I have no idea what's going on under the hood.
Alternatively, you could temporarily assign it to a dummy value in the else block. This adds extra initialization time and memory allocation, so probably not the best idea, but it'll work if you really want to have the property be non-optional.
} else {
self.applescriptLanguage = OSALanguage()
return nil
}