Add a dot in Calculator Swift - ios

I've tried implementing the dot or "point" in calculator I'm programming the windows 7 calculator as a reference to my calcu.
I've tried this in my code:
#IBAction func btnDot(sender: AnyObject) {
if(lblResult.text!.characters.count == 0) {
lblResult.text = "0."
}
else {
if(Float(lblResult.text!.lowercaseString.characters.contains(".")) == -1) {
lblResult.text = lblResult.text! + "."
}
}
lblResult.text = lblResult.text
}
but the function btnDot doesn't seem to work. What seems to be the problem here?
Note: The lblResult.text is the Id of my UILabel for the display of results

Try this code
if (lblResult.text?.characters.count == 0){
lblResult.text = "0."
}
else{
if lblResult.text!.rangeOfString(".") == nil{
lblResult.text = lblResult.text! + "."
}
}
If you want help you with your code you'll need to provide more info about the problem, now I just could give you a working example.

Related

check if a buttons has a set image

I am trying to have a button that checks if it has an icon if so do X other wise do Y
if button.currentImage!.isEqual(UIImage(named: "check")) {
print("X")
} else {
print("Y")
}
Since currentImage could be nil then you need to safely use ? instead of !
if button.currentImage?.isEqual(UIImage(named: "check")) ?? false {
print("X")
} else {
print("Y")
}
if it's only check if image exists then no compare
if button.currentImage != nil {
print("X")
} else {
print("Y")
}

Function in Swift will run, but will not execute "completion" in Swift

I am trying to call a function in Swift. The first time I call it, it runs as intended, but the second time the completion handler if and else statements don't run. Despite this, I still know the function runs because I had it print "RAN" every time it ran. I have no idea what I am doing wrong. Any help?
My Code:
[other code]
self.movieNum = Int(arc4random_uniform(50) + 1)
// Int movieNum is turned into String
let movieNumNSNumber = self.movieNum as NSNumber
let movieNumString: String = movieNumNSNumber.stringValue
self.checkIfMovieHasAlreadyBeenShown(movieID: movieNumString, completion: { seen in
if seen {
var i = 1
var haveAllBeenSeen = 1
while i <= 50 {
let iNSNumber = i as NSNumber
let iString: String = iNSNumber.stringValue
self.checkIfMovieHasAlreadyBeenShown(movieID: movieNumString, completion: { seen in
if seen {
print("SEEN")
}
else {
print("NOT SEEN")
haveAllBeenSeen = 0
}
})
i += 1
}
if haveAllBeenSeen == 0 {
self.swipingView()
}
else {
[other code]
}
else {
return
}
})

How do I check if UIImage is empty in swift?

This is my code but it seems the conditional "if" check for UIImage being empty is not executing. Is it the wrong way of checking if UIImage is empty? I have also tried
if allStyleArrays[i][ii][iii] as UIImage? == nil {
...
}
And not working, please if none of those methods checks, what is the correct way?
Thanks.
Code:
for var i = 0; i <= allStyleArrays.count; i++ {
if i == allStyleArrays.count {
self.performSegueWithIdentifier("toStylistReviewAndConfirm", sender: self)
} else {
for var ii = 0; ii < allStyleArrays[i].count; ii++ {
for var iii = 0; iii < allStyleArrays[i][ii].count; iii++ {
if allStyleArrays[i][ii][iii] as UIImage? == UIImage(named: "") {
} else {
switch i {
case 0:
styleN[0].append(allStyleArrays[i][ii][iii])
//print("style 1 \(style1.count)")
break
case 1:
styleN[1].append(allStyleArrays[i][ii][iii])
//print("style 2 \(style2.count)")
break
default:
styleN[2].append(allStyleArrays[i][ii][iii])
//print("style 3 \(style3.count)")
break
}
}
}
}
}
}
try
if allStyleArrays[i][ii][iii].imageAsset == nil

String to int Button

I'm working on a math multiple choice buttons based swift app. I want to check if the selected button is the correct answer. i have the following code.
let sum = num1.text!.toInt()! + num2.text!.toInt()!
if btn2.titleLabel! == "\(sum)"
{
check.text = "Right"
}
else
{
check.text = "Wrong"
}
it still doesn't work when I click on a answer choice. It says wrong for all
You are comparing the actual UILabel object to the sum and not the text of the label to the sum, so try:
let sum = num1.text!.toInt()! + num2.text!.toInt()!
if btn2.titleLabel!.text == "\(sum)"
{
check.text = "Right"
}
else {
check.text = "Wrong"
}
You should connect your buttons to an #IBAction function.
Keep the sum as an Int. No need to convert it to a String.
The function could look like this.
#IBAction func theButtons(sender: UIButton) {
let p = sender.currentTitle!.toInt()
if sum==p {
check.text = "right"
}
else{
check.text = "wrong"
}
}

CS193P Assignment 1 π

I'm studying CS193P course on iTunesU. I have a question related to the 1st assignment - Programmable Calculator. I've attempted to add the π button as described in the lectures and the homework assignment. However, pressing the π key followed by enter or and operand causes a crash with the message: "fatal error: unexpectedly found nil while unwrapping an Optional value"
class CalculatorBrain
{
private enum Op {
case Operand(Double)
case NullaryOperation(String, () -> Double)
case UnaryOperation(String, Double -> Double)
case BinaryOperation(String, (Double,Double) -> Double)
var description: String{
get {
switch self {
case .Operand(let operand): return "\(operand)"
case .NullaryOperation(let symbol, _): return symbol
case .UnaryOperation(let symbol, _): return symbol
case .BinaryOperation(let symbol,_):return symbol
}
}
}
}
private var opStack = [Op]()
private var knownOps = [String:Op]() //initialize dictionary
init() {
func learnOp (op: Op) {
knownOps[op.description] = op
}
learnOp(Op.BinaryOperation("×", *))
learnOp(Op.BinaryOperation("÷", { $1 / $0 }))
learnOp(Op.BinaryOperation("+", +))
learnOp(Op.BinaryOperation("−", { $1 - $0 }))
learnOp(Op.UnaryOperation("√", sqrt))
learnOp(Op.UnaryOperation("sin", sin))
learnOp(Op.UnaryOperation("cos", cos))
learnOp(Op.NullaryOperation("π", { M_PI }))
}
I've been able to force it in the view controller, but know this is a hack:
var displayValue: Double{
get{
// I don't understand why I had to put this hack in for π
// if (calcDisplay.text != "π"){
return NSNumberFormatter().numberFromString(calcDisplay.text!)!.doubleValue
// } else {
// return M_PI
// }
}
set{
calcDisplay.text = "\(newValue)"
userIsInTheMiddleOfTyping = false
}
}
I'm new to Swift / Obj-C. Can someone please help point me in the right direction to resolve this?
Full source: https://github.com/philnewman/Calculator
#IBAction func appendPi(sender: UIButton) {
let x = M_PI
if userIsInTheMiddleOfTypingANumber {
displayValue = x
display.text = "\(displayValue)"
}else {
displayValue = x
userIsInTheMiddleOfTypingANumber = true
enter()
}
}
Created a new UIButton function for PI separate from the other functions. Working for me, give it a go.
NSNumberFormatter().numberFromString is designed to convert numerical strings into numbers. A "numerical string" is a string whose contents are of the form:
([:digit:]+(\.[:digit:]*)?)|(\.[:digit:]+)
Where [:digit:] is the set of digits {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}.
Essentially, it will only parse numbers from strings whose characters are within 0-9 and an optional ..
Because π doesn't belong to this set of 10 characters, it is rejected and the NSNumberFormatter is unable to parse a number from the string.
I am doing the same course, but as I am not yet at the point of separating my MVC (will do that in the next assignment), I can only give you a hint where you go wrong. As it works for me....
Your hack is testing calcDisplay.text as being "π", however at that moment calcDisplay.text should already be 3,14159.
That is what I checked with a println on my working assignment.
So I can show you part of my code which is not optimal for MVC yet:
case "cos": performOperation{cos($0)}
case "∏": performConstant(operation)
func performOperation (operation: (Double) -> Double) {
if operandStack.count >= 1 {
displayValue = operation(operandStack.removeLast())
enter()
}
}
func performConstant (symbol: (String)) {
switch symbol {
case "∏": displayValue = M_PI
default: break
}
display.text = "\(displayValue)"
enter()
}
I think it can be more optimal too, but it might help you with finding the bug in your code.
I am also doing same course. I did solved "." and "pie" question. See if this help you.
#IBAction func appendDigit(sender: UIButton) {
let digit = sender.currentTitle!
if digit == "." {
if (display.text!.rangeOfString(".") == nil) {
display.text = display.text! + "."
} else {
//Don't display anything
}
} else if digit == "∏" {
displayValue = pie
} else {
if userIsInTheMiddleOfTypingANumber {
display.text = display.text! + digit
} else {
display.text = digit
userIsInTheMiddleOfTypingANumber = true
}
}
}

Resources