HTHorizontalSelectionList unexpectedly found nil while unwrapping an Optional value - swift

..and I'll tell you why:
I'm using the following pod: HTHorizontalSelectionList
If I declare it like this:
class RightViewController: UIViewController, HTHorizontalSelectionListDelegate, HTHorizontalSelectionListDataSource {
var selectionList: HTHorizontalSelectionList!
}
I get the following error on compilation:
ld: warning: directory not found for option '-FTest'
Undefined symbols for architecture x86_64:
"_OBJC_CLASS_$_HTHorizontalSelectionList", referenced from:
__TMaCSo25HTHorizontalSelectionList in RightViewController.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
Huh!? What!?
If I instead implement it like this it compiles fine!
override func viewDidLoad() {
super.viewDidLoad()
var selectionList: HTHorizontalSelectionList!
selectionList?.frame = CGRectMake(0, 0, self.view.frame.size.width, 40)
selectionList?.delegate = self
selectionList?.dataSource = self
self.view.addSubview(selectionList)
}
...except of course, I get an error on the addSubview line:
fatal error: unexpectedly found nil while unwrapping an Optional value
I'm finding it incredibly difficult to understand how Swift works when I get stuff like this happening quite often.

I'm finding it incredibly difficult to understand how Swift works when I get stuff like this happening quite often
There is nothing difficult about this. You are starting out with your Optional variable set to nil. It stays nil. Eventually you try to unwrap nil and then you crash, because you can't do that:
var selectionList: HTHorizontalSelectionList! // it is nil
selectionList?.frame = CGRectMake(0, 0, self.view.frame.size.width, 40) // still nil, nothing happens
selectionList?.delegate = self // still nil, nothing happens
selectionList?.dataSource = self // still nil, nothing happens
self.view.addSubview(selectionList) // unwrap, crash
If you don't want to crash, assign selectionList an actual value other than nil, like maybe an actual HTHorizontalSelectionList.

Related

Crash when unwrapping an optional, but I don't see any optional?

I receive several crash reports:
Bugsnag:
VC.swift:290:34
Swift runtime failure: Unexpectedly found nil while implicitly unwrapping an Optional value
Apple Crash:
Line 290 has following code
func showFolders(path:String, topLevel:Bool = false, absolutePath:String) {
print("đź“‚ Get folder: " + path)
NetworkingService.shared.webdav.contentsOfDirectory(path: path, completionHandler: {
some code
})
}
The function 'showFolders' is called by following code which avoids to send any optional value:
let path = browser_relativePath?.absoluteString.removingPercentEncoding ?? ""
let topLevel = NetworkingService.shared.url_connected.hostOnly.withTrailingSlash == browser_absolutePath?.absoluteString
let absolutePath = browser_absolutePath?.path ?? ""
self.embeddedViewController.showFolders(path:path, topLevel: topLevel, absolutePath: absolutePath)
I don't understand how this might crash by "unwrapping an optional" when there is no optional in that part of the code... But I am probably blind ;-)
Can someone help me out ?
The clue is it says when implicitly unwrapping… so either NetworkingService.shared or NetworkingService.shared.webdav is declared as implicitly unwrapped and is nil when you call it

Unwrapping an Optional value for a Label [duplicate]

This question already has answers here:
What does "Fatal error: Unexpectedly found nil while unwrapping an Optional value" mean?
(16 answers)
Closed 2 years ago.
in this issue i tried to unwrap it by adding ! next verifiedLabel in viewDidLoad to become verifiedLabel!.text but the result is still printing Fatal error: Unexpectedly found nil while unwrapping an Optional value. Thank you
override func viewDidLoad() {
super.viewDidLoad()
verifiedLabel.text = "" }
self.verifiedLabel.text = user.isPhoneVerified ? "Verified" : "Not Verified" }
You are force unwrapping an optional by adding a !, so if the value is null like it is in your case the program will crash.
To unwrap an optional in a safe way (for a generic case) follow this method from Hacking With Swift:
var name: String? = nil
if let unwrapped = name {
print("\(unwrapped.count) letters")
} else {
print("Missing name.")
}
In your SPECIFIC case however verifiedLabel is likely your label set on a storyboard. So you can unwrap it like var verifiedLabel:UILabel! since the value should NOT be null.
So now since its null, a) please check your outlet connections and if everything looks good b) check this thread for debugging: IBOutlet is nil, but it is connected in storyboard, Swift

Want to set Slidervalue to a UserDefault: Thread 1: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value [duplicate]

This question already has answers here:
What does "Fatal error: Unexpectedly found nil while unwrapping an Optional value" mean?
(16 answers)
Closed 2 years ago.
My problem is that I want to set the value of a slider to a UserDefault. In the first version of the app everything worked fine and I use the same code in version 2. Now Xcode shows the error "Thread 1: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value", but I never have used Optionals in the code. I have updated Xcode, maybe there is a problem.
Thank you in advance
func speichernNutzerEinstellungenIntervall(){
standard.set(zeitInsgesamt, forKey: Keys.speichernZeitInsgesamt)
}
func überprüfenLängeIntervall(){
let speichernZeitInsgesamt = standard.integer(forKey: Keys.speichernZeitInsgesamt)
zeitInsgesamt = speichernZeitInsgesamt
sliderIntervallOutlet.setValue(Float(zeitInsgesamt), animated: true) //Here I get the error}
(I have declared the variable "zeitInsgesamt" as a global variable. Don't know if this is important.)
The value of sliderIntervallOutlet is nil. Try to check nil value for property before set any value. Like this
func überprüfenLängeIntervall(){
let speichernZeitInsgesamt = standard.integer(forKey: Keys.speichernZeitInsgesamt)
zeitInsgesamt = speichernZeitInsgesamt
if sliderIntervallOutlet != nil {
sliderIntervallOutlet.setValue(Float(zeitInsgesamt), animated: true)
}
}

Swift assert() not working with simple comparison to nil

This is driving me banerners.
Here's the XCode 6.4 autocomplete from typing assert in Swift:
assert(condition: Bool, message: String)
Here's how I'm using it in my init:
required init (mainController: MainVC) {
assert(mainController.parameterThatShouldNotBeNil != nil,
"oops parameterThatShouldNotBeNil is nil")
super.init()
}
Here's the error message from the little red exclamation point:
Cannot invoke 'assert' with an argument list of type '(Bool, String)'
...has me pulling my hair out. Double You Tee Eff?
EDIT
Here's a short example that can be pasted into XCode:
class HasNoNil {
var definitelyNotNil: String = "nope not nil"
}
class ChecksForANil{
init (objectToCheck: HasNoNil){
assert(objectToCheck.definitelyNotNil != nil, "whoops it actually is nil")
}
}
That gives the same error I'm seeing.
The underlying problem is that Swift can't compare a non-Optional value with nil, basically because that comparison doesn't make sense: it's not Optional, so it can't possibly be nil, and you can work that out at compile time (or rather, there's no overload for != set up between non-Optional and nil, because there doesn't need to be.)
If you try a simpler example without the assert:
class HasNoNil {
var definitelyNotNil: String = "nope not nil"
}
class ChecksForANil{
init (objectToCheck: HasNoNil){
if (objectToCheck.definitelyNotNil != nil) { println("Not nil") }
// assert(objectToCheck.definitelyNotNil != nil, "Hrm")
}
}
...you'll get a more sensible error: "Could not find an overload for '!=' that accepts the supplied arguments". (Xcode 6.2/Swift 1.2) If you make definitelyNotNil an Optional, then everything works fine.
So, I think this is just a misleading error message. Sadly, this type of misleading error, when the problem is with the parameters to a function, seems quite prevalent in early Swift compilers. You might want to try it under Swift 2 and raise a report with Apple if it's not fixed already.

Dictionary updateValue causes swift compiler segmentation fault

My class has a property
var activeSquares = Dictionary <String, SKShapeNode> ()
I try to add and update values in the dictionary using
let squareNode = SKShapeNode(rectOfSize: CGSizeMake(80, 80), cornerRadius: 8)
activeSquares.updateValue(squareNode, forKey: "someUniqueDescription")
I also get the same crash if I use
activeSquares["someUniqueDescription"] = squareNode
But it is causing a crash when compiling
1. While emitting IR SIL function #_TFC14gamename9GameScene11addedSquarefS0_FCS_6SquareT_ for 'addedSquare' at /.../gamename/gamename/GameScene.swift:30:5
<unknown>:0: error: unable to execute command: Segmentation fault: 11
<unknown>:0: error: swift frontend command failed due to signal (use -v to see invocation)
Command /Applications/Xcode6-Beta2.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swift failed with exit code 254
How do I properly use updateValue to add/update key/value pairs to my dictionary?
No sure if my solution fits here, but it could help. Seems there's something weird with subscription for NSDictionary. Not sure why, but it's defined as:
func objectForKeyedSubscript(key: NSCopying!) -> AnyObject!
so, if I'm not wrong it returns implicitly unwrapped optional, but should return optional, as far as there could be no value for a key. If you try to write:
if(dictionary["key"] != nil)
you'll get a compile error "AnyObject is not convertible to UInt8" while if you write:
if(dictionary["key"])
you don't get one.
The way I solved this issue was using optional unwrapping, so:
if(someBool && dictionary["key"]) // fine in beta 2, crash in beta 3-4
// turned to:
var hasValueForKey = false
if dictionary["key"]
{
hasValueForKey = true
}
if(someBool && hasValueForKey) // fine in beta 4
and:
var someArray : NSArray? = dictionary["key"]? as? NSArray // note ? after []
I guess there could be something with optionals and stuff for setting an object via subscript, it's defined as:
func setObject(obj: AnyObject!, forKeyedSubscript key: NSCopying!)
Maybe playing with optional unwrapping could help here as well.