NSTextField: Converting String to Int aborts (nil) outside of Xcode - swift

I have a MacOS app that has been working fine for around a year. An NSTextField on a screen containing 20 NSTextFields started aborting with "unexpectedly found nil while unwrapping an Optional value". So far, I've done the following:
Removed and reassigned the textfield's IBOutlet link
Deleted and rebuilt the textfield
This fixes the app when I run in Xcode in my Development account. When I generate an archive and transfer it to my Production account, it still aborts.
I'm going to assume this is still the culprit, since I don't really get much from the core dump (because I probably don't understand what I'm looking at).
Here's my code. (game_number is an Int)
game_number = Int(gameNumberTextField.stringValue)!
When I split the code and do this:
let theNumber = (gameNumberTextField.stringValue)!
game_number = Int(theNumber)
theNumber is a String and correct, but game_number is nil

NSTextField parent class NSControl has a property called integerValue which returns an Int:
game_number = gameNumberTextField.integerValue

You should unwrap the optional value like this:
guard let theNumber = gameNumberTextField.integerValue else {
// Value not found, handle this case
return
}
Hope this helps!

Related

Casting an Int as a String from a Realm result Swift

I am asking this hesitantly as I know this is probably a dumb question.
I am returning a Realm result and then have gone ahead and tried to cast it to a String as normal (to put in a text label).
However I'm getting an error 'init' has been renamed to 'init(describing:)'.
When I try use the describing method instead, the label prints "Optional" inside it which obviously isn't what I want.
Is there a reason I can't use :
previousTimeLabel.text = String(lastRecord?.time)
I'm sure I've done this before and it's been fine, am I missing something? (lastRecord.time is an Int).
I've checked the answer here about Interpolation Swift String Interpolation displaying optional? and tried changing to something like this :
if let previousRounds = String(lastRecord?.rounds) {
previousRoundsLabel.text = previousRounds
}
but get the same error + Initializer for conditional binding must have Optional type, not 'String'
The issue isn't String(lastRecord?.time) being Optional. The issue is lastRecord being Optional, so you have to unwrap lastRecord, not the return value of String(lastRecord?.time).
if let lastRecord = lastRecord {
previousRoundsLabel.text = "\(lastRecord.time)"
}
To summarize Dávid Pásztor's answer, here's a way you can fix it:
previousTimeLabel.text = String(lastRecord?.time ?? 0)
This may not be the best way for your application. The point Dávid was making is that you need to deal with lastRecord possibly being nil before trying to pass its time Int into the String initializer. So the above is one simple way to do that, if you're ok with having "0" string as your previousTimeLabel's text if there was no lastRecord.

Swift 3 cast UITextField to Int

I'm receiving a compiler error and I'm not really sure why. I'm sure there is a simple answer for this. I have a core data attribute I'm trying to assign before saving. In my Core Data Property file it's defined as this:
#NSManaged public var age: Int32
I am using a UIPicker to select it and put it into an inputView. That works fine, so ageTextField: UITextField! holds the value. As I try to assign this to the CoreData object just before saving I get the following
person.age = ageTextField.text -> Cannot assign String? to Int32.
Ok, I understand that, so I cast it
person.age = Int(ageTextField.text) -> Value of Optional String not unwrapped...
Ok, I get that, so I unwrapped it, it asks to unwrap again and I agree:
person.age = Int(ageTextField.text!)! -> Type of expression is ambiguous without more context
I'm not sure what is wrong here, just looking over some old Swift 2 code of mine and this worked. This is my first code with Swift 3 though.
That compiler error is obscure at best and misleading at worst. Change your cast to Int32:
person.age = Int32(ageTextField.text!)!
Also: unless you are absolutely sure that the user will always enter a valid number into the textfield, use optional binding instead of force unwrap:
if let text = ageTextField.text,
let age = Int32(text)
{
person.age = age
}
The immediate issue is the use of the wrong type. Use Int32, not Int. But even once that is fixed, you have lots of other issues.
You should safely unwrap the text and then the attempt to convert the string to an integer.
if let text = ageTextField.text, let num = Int32(text) {
person.age = num
}
The use of all of those ! will cause a crash if the text is nil or it contains a value that isn't a valid number. Always use safe unwrapping.
Just make sure to unwrap the optional before convert. Make your code safe.

Swift 2.2: Optional Binding in a function

Heys guys,
I am pretty new into programming and therefore I've followed I course on Udemy to teach me Swift 2.2.
For learning purpose I have been trying to program a BMI-calculator where I have a textfield (which just displays the value) and a slider where I can put my weight in kg. After dragging the slider the value is visible in the textfield. I cannot put a value into the textfield so that it is displayed on the slider!
The same textfield-slider relation is used with the height in cm. Now I created an IBAction the bring my kgSlider.value into my kgField.text and it looks like this:
#IBAction func kgSet(sender: AnyObject) {
kgField.text! = String(Int(kgSlider.value))
}
Thats works fine but I unwrapped (like the teacher in the course) without knowing, if there really is a value. Okay, I know in this case that there will be a value, but I would like to go more real and therefore I tried to use an Optional-Binding to find out, if there is a value instead of directly unwrap it.
Therefore I used the cm.Field and the cm.Slider in my code but it doesn't work for now and I don't know why. The code is the following:
#IBAction func cmSet(sender: AnyObject) {
if let tempCm = String(Int(cmSlider.value)) as String! {
cmField.text = tempCm
}
}
So I created the constant called tempCM which will got the value from the cmSlider, if there is a value. Therefore I casted the cmSlider.value like in the other IBAction into an Int and then into a String. If there is the value it will carry it into the cmField.text. This didn't work, therefore I tried to use the "as String!" statement but know I get always 0 instead of the correct value.
So what am I doing wrong there?
So, this should compile fine and provide you with your desired result.
#IBAction func cmSet(sender: AnyObject) {
if let tempCm = String(Int(cmSlider.value)) {
cmField.text = tempCm
}
}
You could also try this
cmField.text = String(Int(cmSlider.value)) ?? " "
in the second example, you are using the optional operator to say if you can convert this to an Int then that Int to a string set the cmField.text property to its value, otherwise use a blank space as the default value.

Winter 2015 / Lecture 10 - Broken Twitter Package

Trying to follow along and code the Smashtag project while watching the Lecture 10 iTunes video.
When I add the dowloaded Twitter package to my Smashtag project, XCode couldn't find the Tweet class when I made reference to it in the TweetTableViewController.
Because of the problem described above, I added the four classes belonging to the Twitter package individually to the project. XCode found the four classes but adding them in this manner generated 11 compile errors.
I'm using XCode Version 6.3 (6D570) which is subsequent to the iOS 8.3 release.
Has anyone else encountered this issue?
Thank you for reading my question.
~ Lee
Possibly not the most-correct (read: best practice) way to do this, but I'm going to chalk it up to doing what it takes to finish the course.
I just went through the list of compile errors and changed the relevant properties to var instead of let. Constants can't be changed and in the new version of Swift they can only be instantiated once. So for the sake of not rewriting too much code, I chose to make certain properties vars instead of lets.
Other bugs I found following the iTunes U course:
The named ‘handler:’ argument needs the name explicitly in a few places.
The simulator will show "TwitterRequest: Couldn\'t discover Twitter account type.” until you go to Settings (inside the simulator) and set the Twitter account. At this point I had to reboot the device, as the call is made in the ViewDidLoad, and thus is only called the first time the view loads. (Alternatively, you could close out the app from the app switcher in the simulator and relaunch that way.)
Here is a gist with corrected code that you can use as a Twitter package that will work with the course and has fixes for the aforementioned bugs, minus the Twitter account setting:
https://gist.github.com/mattpetters/ccf87678ccce0c354398
As Christian R. Jimenez said, "I went to Settings in the Simulated iphone and add my Twitter Account. And everything works perfect." in http://cs193p.m2m.at/cs193p-lecture-10-table-view-winter-2015/. I just added my Twitter Account and tested it, it works!
I had similar problems with the Twitter packages using Swift 2.0 and Xcode 7.2
I'm very new to Swift, so there is a good chance the changes I made are not best practices, but the updated files do work: https://gist.github.com/awaxman11/9c48c0b4c622bffb879f.
For the most part I used Xcode's suggested changes. The two larger changes I made were:
In Tweet.swift I updated the the IndexedKeyword struct's init method to use advanceBy() instead of advance()
In TwitterRequest.swift I updated the signature of NSJSONSerialization to conform to the new error handling system
I've just had a big session fixing the Twitter package files for this same version of Xcode.
It seems that what has broken is that in this version of Swift, constants ('let x...') may only be initialized once, so if a constant is given a value in the declaration ('let x = false'), it may not be changed in the init() function. The Twitter package gives some constants initial values, but then changes the values in the init() function.
My solution to this was to follow the styles suggested in the current version of the Apple Swift language book: declare (many of) the constants as implicitly unwrapped optionals, unconditionally assign a value to them in the init() function (which value may be nil), then test whether any of them are nil, and, if so, return nil from init().
See https://developer.apple.com/library/mac/documentation/Swift/Conceptual/Swift_Programming_Language/Initialization.html, click "On This Page" and choose "Failable Initializers"
Also, in TwitterRequest.swift, I needed to add the parameter name 'handler:' in a couple of calls to performTwitterRequest(request, handler: handler).
As an example of constant initialization, in MediaItem.swift:
<< Original Code >>
...
public let aspectRatio: Double = 0
...
init?(data: NSDictionary?) {
var valid = false
if let urlString = data?.valueForKeyPath(TwitterKey.MediaURL) as? NSString {
if let url = NSURL(string: urlString) {
self.url = url
let h = data?.valueForKeyPath(TwitterKey.Height) as? NSNumber
let w = data?.valueForKeyPath(TwitterKey.Width) as? NSNumber
if h != nil && w != nil && h?.doubleValue != 0 {
aspectRatio = w!.doubleValue / h!.doubleValue
valid = true
}
}
}
if !valid {
return nil
}
}
...
<< Updated code >>
...
public let aspectRatio: Double
...
init?(data: NSDictionary?) {
if let urlString = data?.valueForKeyPath(TwitterKey.MediaURL) as? NSString {
if let url = NSURL(string: urlString as String) {
self.url = url
let h = data?.valueForKeyPath(TwitterKey.Height) as? NSNumber
let w = data?.valueForKeyPath(TwitterKey.Width) as? NSNumber
if h != nil && w != nil && h?.doubleValue != 0 {
aspectRatio = w!.doubleValue / h!.doubleValue
return
}
}
}
return nil
}
...

Can't figure out how to add two CGFloats?

I'm getting this error "Cannot invoke '+' wit an argument list of type '(CGFloat, CGFloat)' when using this Swift code.
var added = CGFloat(gestureRecognizer.view?.center.y) + CGFloat(translation.y)
What am I doing wrong. I have two floats and I want to add them together.
This line here:
gestureRecognizer.view?.center.y
Can be thought of as an expression that returns a CGFloat? optional. If view is nil, it returns nil. If view has a value, it drills in. And CGFloat(nil) is a compile error.
var added = CGFloat(gestureRecognizer.view!.center.y) + CGFloat(translation.y)
// ^ ! instead of ?
You really want to unwrap it here. Because if view is nil you pass nil to CGFloat() which isn't gonna be cool. But you do have to think about what might happen when view is nil.
Perhaps that will never happen in the flow of your program, I don't know. But if it is nil that will cause a runtime crash.