This might be a newbie question

I downloaded and built the latest compiler, which would be this:

Swift version 5.6-dev (LLVM ae102eaadf2d38c, Swift e7342eb87849367)
Target: aarch64-unknown-linux-gnu

I then wrote a simple program , and I wonder if I have forgotten Swift already after a time spent writing C++.
Should this actually be giving an error?

var dict : [AnyHashable: Any]!
dict["asdf" ] = 3
dict[3] = "asdf" 
for (key,val) in dict {
	print ("\(key) -> \(val)")
}

This produces:

foo/foo.swift:5: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value

Yes, the dictionary is uninitialized, but implicitly unwrapped.
Try setting it to [:] before adding an entry.

1 Like

It took me an untrivial amount of time (more than a few seconds, maybe it's too late here) to spot the error in the original example. And I don't want to derail this thread, but I couldn't help but think that, well, this is a point in favor of "Pre-pitch: remove the implicit initialization of Optional variables" in my book...

2 Likes

Also, there is no need to use an implicitly unwrapped optional here. Instead, use this:

var dict : [AnyHashable: Any] = [:]
dict["asdf" ] = 3
dict[3] = "asdf"
for (key,val) in dict {
    print ("\(key) -> \(val)")
}
1 Like

Most pitches for removing the implicit Type? initialization leave IUO behavior in place, as the IUO feature is supposed to have this behavior. Otherwise it would be pretty useless.

2 Likes

I think the problem is single-character modifiers. Back in the days of old, I think there was a language that used a lot of them, perhaps APL? They had single characters for intuitive things like sqrt function, and many symbols that people found unintuitive like a triangle symbol.
Coming as I recently am from C++, the precise meaning of the "!" modifier might may have slipped my memory, especially since memory management in C++ is partly DIY.

Terms of Service

Privacy Policy

Cookie Policy