Unable to calculate with Optional Variables - swift

I have a simple App with 2 text fields
User just needs to enter Year of Service and Salary
I just need to multiply them.
Would like to output to a text label
(1) I have checked for a nil, and code passes
(2) but I am unable to convert the value to Int for multiplication
(3) debugged section by merely multiplying the Int(UserInputVariable.txt) * any number
(4) and just print. No output to debugging screen
if let var1 = Int(staffYrOfServiceTextField.text!) {
let mult = var1 * 3
print(mult)
}
I expected output to debugging screen

You never "verify" that var1 is not nil in the output debugger.
if let var1 = Int(staffYrOfServiceTextField.text!) {
let mult = var1 * 3
print(mult)
} else {
// If reach here, then Int(staffYrOfServiceTextField.text!) is nil.
print(staffYrOfServiceTextField.text)
print("staffYrOfServiceTextField text does not conform to int or is nil")
}

As per your problem statement, there could be two ways to solve this:
1) When you have the textField's keyboard type only numeric, where you are sure about the input will definitely be integer only.
if let salary = txtFld_Salary.text, let exp = txtFld_YearOfExperience.text {
let multi = Int(salary)! * Int(exp)!
print(multi)
}
2) If you havn't defined the keyboard type and user may enter string values in those then use below code to get the multiplication:
if let salary = txtFld_Salary.text, let exp = txtFld_YearOfExperience.text {
if let intSalary = Int(salary), let intExp = Int(exp) {
let multi = intSalary * intExp
print(multi)
}
}

Related

String convert to Int and replace comma to Plus sign

Using Swift, I'm trying to take a list of numbers input in a text view in an app and create a sum of this list by extracting each number for a grade calculator. Also the amount of values put in by the user changes each time. An example is shown below:
String of: 98,99,97,96...
Trying to get: 98+99+97+96...
Please Help!
Thanks
Use components(separatedBy:) to break up the comma-separated string.
Use trimmingCharacters(in:) to remove spaces before and after each element
Use Int() to convert each element into an integer.
Use compactMap (previously called flatMap) to remove any items that couldn't be converted to Int.
Use reduce to sum up the array of Int.
let input = " 98 ,99 , 97, 96 "
let values = input.components(separatedBy: ",").compactMap { Int($0.trimmingCharacters(in: .whitespaces)) }
let sum = values.reduce(0, +)
print(sum) // 390
For Swift 3 and Swift 4.
Simple way: Hard coded. Only useful if you know the exact amount of integers coming up, wanting to get calculated and printed/used further on.
let string98: String = "98"
let string99: String = "99"
let string100: String = "100"
let string101: String = "101"
let int98: Int = Int(string98)!
let int99: Int = Int(string99)!
let int100: Int = Int(string100)!
let int101: Int = Int(string101)!
// optional chaining (if or guard) instead of "!" recommended. therefore option b is better
let finalInt: Int = int98 + int99 + int100 + int101
print(finalInt) // prints Optional(398) (optional)
Fancy way as a function: Generic way. Here you can put as many strings in as you need in the end. You could, for example, gather all the strings first and then use the array to have them calculated.
func getCalculatedIntegerFrom(strings: [String]) -> Int {
var result = Int()
for element in strings {
guard let int = Int(element) else {
break // or return nil
// break instead of return, returns Integer of all
// the values it was able to turn into Integer
// so even if there is a String f.e. "123S", it would
// still return an Integer instead of nil
// if you want to use return, you have to set "-> Int?" as optional
}
result = result + int
}
return result
}
let arrayOfStrings = ["98", "99", "100", "101"]
let result = getCalculatedIntegerFrom(strings: arrayOfStrings)
print(result) // prints 398 (non-optional)
let myString = "556"
let myInt = Int(myString)

Performing functions with valueForKey

I am trying to get my app to perform functions. I have two attributes per item (quantity and price) that I want to multiply together and then total for all the didSelectRow items on the list. There is two sections on my tableView. Section 0 is regular and moved to section 1 with didSelectRow. (I only explain this because it comes into play further down)
My code so far is...
`func cartTotalFunc() {
itemFetchRequest().returnsObjectsAsFaults = false
do {
let results = try moc.executeFetchRequest(itemFetchRequest())
print("===\(results)")
// Calculate the grand total.
var grandTotal = 0
for order in results {
let SLP = order.valueForKey("slprice") as! Int
let SLQ = order.valueForKey("slqty") as! Int
grandTotal += SLP * SLQ
}
print("\(grandTotal)")
cartTotal.text = "$\(grandTotal)" as String
} catch let error as NSError {
print(error)
}
}
`
slprice and slqty are strings in Core Data. I am trying to cast them as Int so they will do the arithmetic. I had this working but it totaled every item instead of only the crossed off ones (section 1). I gave it a rest for a while and now when I come back to try to work on it again Xcode is giving me an error of, "can not Could not cast value of type 'NSTaggedPointerString' (0x104592ae8) to 'NSNumber' (0x1051642a0)."
Can anyone help with this, please?

Why in swift are variables option in a function but not in playground

I am puzzled. I need to compare product date codes. they look like 12-34-56. I wrote some code to break the parts up and compare them. this code works fin in the play ground. But when i make it a function in a view controller values come up NIL and i get a lot of "Optional("12-34-56")" values when printed to the log or viewed in a break. I tried unwrapping in many locations but nothing takes.? don't be confused by the variables date and month because they are not product codes can have 90 days and 90 months depending on the production machine used.
func compaireSerial(oldNumIn: NSString, newNumIn: String) -> Bool {
// take the parts of the number and compare the pics on at a time.
// Set up the old Num in chunks
let oldNum = NSString(string: oldNumIn)
let oldMonth = Int(oldNum.substringToIndex(2))
let oldDay = Int(oldNum.substringWithRange(NSRange(location: 3, length: 2)))
let oldYear = Int(oldNum.substringFromIndex(6))
print(oldMonth,oldDay, oldYear)
// Set up the new Num in chunks
let newNum = NSString(string: newNumIn)
let newMonth = Int(newNum.substringToIndex(2))
let newDay = Int(newNum.substringWithRange(NSRange(location: 3, length: 2)))
let newYear = Int(newNum.substringFromIndex(6))
print(newMonth, newDay, newYear)
// LETS Do the IF comparison steps.
if oldYear < newYear {
return true
} else if oldMonth < newMonth {
return true
} else if oldDay < newDay {
return true
} else {
return false
}
}
May thanks to any one. Im totally stumped
All Int() initializers with String parameters return always an optional Int.
The realtime result column in a Playground doesn't indicate the optional but printing it does.
let twentyTwo = Int("22") | 22
print(twentyTwo) | "Optional(22)\n"
I don't see how i can delete my question so ill post this to let others know it is fixed. Turns out the auction works okay but the NSUserDefaults value coming in was optional. So i was feeding the optional in. After unwrapping the NSUser value all works.

Converting String to Int in Swift

Hello I'm new to Swift and I'm building a calculator in Xcode. In my main storyboard I have a UIButton, UILabel and a UITextField that will get a number and by pressing the button, label's text should show the entered number + 5. In my app I need to convert a String variable to Int.
I tried the snippet below I didn't get any meaningful result.
var e = texti.text
let f: Int? = e.toInt()
let kashk = f * 2
label.text = "\(pashm)"
To make it clean and Swifty, I suggest this approach:
Swift 2 / 3
var string = "42" // here you would put your 'texti.text', assuming texti is for example UILabel
if let intVersion = Int(string) { // Swift 1.2: string.toInt()
let multiplied = 2 * intVersion
let multipliedString = "\(multiplied)"
// use the string as you wish, for example 'texti.text = multipliedString'
} else {
// handle the fact, that toInt() didn't yield an integer value
}
If you want to calculate with that new integer you have to unwrap it by putting an exclamation mark behind the variable name:
let stringnumber = "12"
let intnumber:Int? = Int(stringnumber)
print(intnumber!+3)
The result would be:
15
var string = "12"
var intVersion = string.toInt()
let intMultipied = intVersion! * 2
label.text= "\(intMultipied)"
Regarding how to convert a string to a integer:
var myString = "12" //Assign the value of your textfield
if let myInt = myString.toInt(){
//myInt is a integer with the value of "12"
} else {
//Do something, the text in the textfield is not a integer
}
The if let makes sure that your value can be casted to a integer.
.toInt() returns an optional Integer. If your string can be casted to a integer it will be, else it will return nil. The if let statement will only be casted if your string can be casted to a integer.
Since the new variable (constant to be exact) is a integer, you can make a new variable and add 5 to the value of your integer
var myString = "12" //Assign the value of your textfield
if let myInt = myString.toInt(){
//myInt is a integer with the value of “12”
let newInt = myInt + 5
myTextfield.text = "\(newInt)"
//The text of the textfield will be: "17" (12 + 5)
} else {
//Do something, the text in the textfield is not a integer
}

Swift NSString to Int conversion issues

First off, I'm fairly new to programming and trying to learn Swift, though I've worked with python and perl in the past.
I'm creating a simple prime number command line application. The program runs correctly when I provide the arguments for the functions, but causes consistently incorrect outputs when I prompt user input. I researched the best way to implement this behavior in Swift, as it doesn't have scanf() or raw_input() type commands, but I have something screwed up.
The program has several different functions, but the one I've been fighting with checks whether an integer is prime. The code for the function follows:
func testForPrime(num:Int)->Bool{
var num = num
var counter = 0
var primeTest : Bool = true
if num <= 1 || num % 2 == 0{
println("\(num) is not a prime number")
primeTest = false
}else{
##'checkerNumbers' is another function to determine the denominator
for i in checkerNumbers(Double(num)){
if num % i == 0 {
++counter
println("\(num) is not a prime number.")
println("\(num / i)*\(i)=\(num)")
primeTest = false
break
}
}
if counter == 0{
println("\(num) is a prime number!")
primeTest = true
}
}
return primeTest
}
And here is the input for the function:
var input = NSFileHandle.fileHandleWithStandardInput()
println("Enter a number to check if it is prime")
if let data : NSData = input.availableData as NSData? {
if let var x : Int = NSInteger(NSUTF8StringEncoding) as NSInteger?{
var intInput = x
testForPrime(intInput)
}
}
When a any number is entered in the terminal, the output is always '4'. However, if I run the function with testForPrime(13), instead of with user input, it responds as I would expect. I was thinking it may have to do with the conversion from NSString and NSUTF8StringEncoding to Int...
Can someone help me sort this out?
Thanks in advance!
Ok... So I figured out a way to make it work, though it may not be the best. I replaced the whole input section with the following:
println("Enter a number to check if it is prime")
var input = NSString(data: NSFileHandle.fileHandleWithStandardInput().availableData, encoding:NSUTF8StringEncoding)
var intInput = input?.intValue
testForPrime(Int(intInput!))