Making a binary calculator app (swift) - ios

For a project in Uni I decided to make a binary calculator app to learn a little bit more about coding.
I've come as far as completing a regular calculator app (but it only has two numbers: 1 ; 0) but I can't figure out how to make the calculator work like it should ( 1010 + 1101 = 10111 not 2111). All help is appreciated.
var numberEkraanil:Double = 0;
var eelmineNumber:Double = 0;
var tehesmatemaatikat = false
var operation = 0;
#IBOutlet weak var label: UILabel!
#IBAction func Numbers(_ sender: UIButton) {
if tehesmatemaatikat == true
{
label.text = String(sender.tag-1)
numberEkraanil = Double(label.text!)!
tehesmatemaatikat = false
}
else
{
label.text = label.text! + String(sender.tag-1)
numberEkraanil = Double(label.text!)!
}
}
#IBAction func nupud(_ sender: UIButton) {
if label.text != "" && sender.tag != 6 && sender.tag != 8
{
eelmineNumber = Double(label.text!)!
if sender.tag == 3 //Liitmine
{
label.text = "+";
}
else if sender.tag == 4 //Lahutamine
{
label.text = "-";
}
else if sender.tag == 5 // Korrutamine
{
label.text = "x";
}
else if sender.tag == 7 // Jagamine
{
label.text = "÷";
}
operation = sender.tag
tehesmatemaatikat = true;
}
else if sender.tag == 8
{
if operation == 3
{
label.text = String(eelmineNumber + numberEkraanil)
}
else if operation == 4
{
label.text = String(eelmineNumber - numberEkraanil)
}
else if operation == 5
{
label.text = String(eelmineNumber * numberEkraanil)
}
else if operation == 7
{
label.text = String(eelmineNumber / numberEkraanil)
}
}
else if sender.tag == 6
{
label.text = ""
eelmineNumber = 0;
numberEkraanil = 0;
operation = 0;
}

You can possibly convert binary numbers to decimal numbers. For example turn "1010" into int "10" and then reverse the process to get the binary again. In your example "1010 + 1101 = 10111" you can convert "1010" and into "10" and "13", make the ordinary calculation with those decimals and convert the result "23", which will give you "23".
But of course there are other ways. This website can help you with binary calculation. It's a math website: http://www.calculator.net/binary-calculator.html.

You will need to write a base 10 to base 2 and a base 2 to base 10 converter. Here is pseudo-code for both:
To convert a binary string to an integer, do the following:
Seed a result value to zero.
while your input string is not empty:
shift the result value 1 bit to the left
remove the left-most character from your input string, and if it's a 1, add 1 to your result value.
To convert an int to a binary string, do the same in reverse:
Copy your int to a scratch variable, scratch.
Set your output string to an empty string.
While scratch is not 0:
if scratch && 1 is 0, append a "0" to the left of your output string
if scratch && 1 is 1, append a "1" to the left of your output string
shift scratch 1 bit to the right
Once you have those building-blocks getting your calculator to work is pretty straightforward. When the user inputs a binary string, convert it to an integer working value. Do your calculations on integer values, and then convert the integer result to a binary string for display.

Related

How many alphabets and numbers special characters in textfield [duplicate]

I want to count the number of letters, digits and special characters in the following string:
let phrase = "The final score was 32-31!"
I tried:
for tempChar in phrase {
if (tempChar >= "a" && tempChar <= "z") {
letterCounter++
}
// etc.
but I'm getting errors. I tried all sorts of other variations on this - still getting error - such as:
could not find an overload for '<=' that accepts the supplied arguments
For Swift 5 see rustylepord's answer.
Update for Swift 3:
let letters = CharacterSet.letters
let digits = CharacterSet.decimalDigits
var letterCount = 0
var digitCount = 0
for uni in phrase.unicodeScalars {
if letters.contains(uni) {
letterCount += 1
} else if digits.contains(uni) {
digitCount += 1
}
}
(Previous answer for older Swift versions)
A possible Swift solution:
var letterCounter = 0
var digitCount = 0
let phrase = "The final score was 32-31!"
for tempChar in phrase.unicodeScalars {
if tempChar.isAlpha() {
letterCounter++
} else if tempChar.isDigit() {
digitCount++
}
}
Update: The above solution works only with characters in the ASCII character set,
i.e. it does not recognize Ä, é or ø as letters. The following alternative
solution uses NSCharacterSet from the Foundation framework, which can test characters
based on their Unicode character classes:
let letters = NSCharacterSet.letterCharacterSet()
let digits = NSCharacterSet.decimalDigitCharacterSet()
var letterCount = 0
var digitCount = 0
for uni in phrase.unicodeScalars {
if letters.longCharacterIsMember(uni.value) {
letterCount++
} else if digits.longCharacterIsMember(uni.value) {
digitCount++
}
}
Update 2: As of Xcode 6 beta 4, the first solution does not work anymore, because
the isAlpha() and related (ASCII-only) methods have been removed from Swift.
The second solution still works.
Use the values of unicodeScalars
let phrase = "The final score was 32-31!"
var letterCounter = 0, digitCounter = 0
for scalar in phrase.unicodeScalars {
let value = scalar.value
if (value >= 65 && value <= 90) || (value >= 97 && value <= 122) {++letterCounter}
if (value >= 48 && value <= 57) {++digitCounter}
}
println(letterCounter)
println(digitCounter)
For Swift 5 you can do the following for simple strings, but be vigilant about handling characters like "1️⃣" , "④" these would be treated as numbers as well.
let phrase = "The final score was 32-31!"
var numberOfDigits = 0;
var numberOfLetters = 0;
var numberOfSymbols = 0;
phrase.forEach {
if ($0.isNumber) {
numberOfDigits += 1;
}
else if ($0.isLetter) {
numberOfLetters += 1
}
else if ($0.isSymbol || $0.isPunctuation || $0.isCurrencySymbol || $0.isMathSymbol) {
numberOfSymbols += 1;
}
}
print(#"\#(numberOfDigits) || \#(numberOfLetters) || \#(numberOfSymbols)"#);
I've created a short extension for letter and digits count for a String
extension String {
var letterCount : Int {
return self.unicodeScalars.filter({ CharacterSet.letters.contains($0) }).count
}
var digitCount : Int {
return self.unicodeScalars.filter({ CharacterSet.decimalDigits.contains($0) }).count
}
}
or a function to get a count for any CharacterSet you put in
extension String {
func characterCount(for set: CharacterSet) -> Int {
return self.unicodeScalars.filter({ set.contains($0) }).count
}
}
usage:
let phrase = "the final score is 23-13!"
let letterCount = phrase.characterCount(for: .letters)
In case you only need one information (letter or number or sign) you can do it in one line:
let phrase = "The final score was 32-31!"
let count = phrase.filter{ $0.isLetter }.count
print(count) // "16\n"
But doing phrase.filter several times is inefficient because it loops through the whole string.

Integers Larger than Int64

I'm attempting to get a user input number and find the sum of all the digits. I'm having issues with larger numbers, however, as they won't register under an Int64. Any idea as to what structures I could use to store the value? (I tried UInt64 and that didn't work very well with negatives, however, I'd prefer something larger than UInt64, anyways. I'm having a hard time implementing a UInt128 from Is there a number type with bigger capacity than u_long/UInt64 in Swift?)
import Foundation
func getInteger() -> Int64 {
var value:Int64 = 0
while true {
//we aren't doing anything with input, so we make it a constant
let input = readLine()
//ensure its not nil
if let unwrappedInput = input {
if let unwrappedInt = Int64(unwrappedInput) {
value = unwrappedInt
break
}
}
else { print("You entered a nil. Try again:") }
}
return value
}
print("Please enter an integer")
// Gets user input
var input = getInteger()
var arr = [Int] ()
var sum = 0
var negative = false
// If input is less than 0, makes it positive
if input < 0 {
input = (input * -1)
negative = true
}
if (input < 10) && (input >= 1) && (negative == true) {
var remain = (-1)*(input%10)
arr.append(Int(remain))
input = (input/10)
}
else {
var remain = (input%10)
arr.append(Int(remain))
input = (input/10)
}
}
// Adds numbers in array to find sum of digits
var i:Int = 0
var size:Int = (arr.count - 1)
while i<=size {
sum = sum + arr[i]
i = (i+1)
}
// Prints sum
print("\(sum)")
You can use a string to perform the operation you describe. Loop through each character and convert it to an integer and add to the sum. Be careful to handle errors.

I don't know how to make them add or subtract, its there a way to do so. Basically I want 1"+"3 = 4 but I get 1+3 [duplicate]

This question already has answers here:
Swift - Resolving a math operation in a string
(4 answers)
Closed 6 years ago.
let randsign = Int(arc4random_uniform(2) + 1)
//This function returns a random operator
func whatSign(par1:Int)-> String {
if (par1 == 1){
return "+"
}
else {
return "-"
}
}
var sigh = whatSign(par1: randsign)
let randnum1:Any = Int (arc4random_uniform(10) + 1)
let randnum2:Int = Int (arc4random_uniform(10) + 1)
//I want the variable "finVal" to perform mathematical operation, but it does not because the variable "sign" is String
let finVal = "\(randnum1)\(sigh)\(randnum2)"
print(finVal)
//When I print I get for example 1-3, 9-4, 8+2 .But I wanted them to do arithmetic
NSExpression is one the good way to evaluate the Math
let finVal = "(randnum1)(sigh)(randnum2)"
let result = NSExpression(format: finVal).expressionValue(with: nil, context: nil) as! Int
let randsign = Int(arc4random_uniform(2) + 1)
let randnum1:Any = Int (arc4random_uniform(10) + 1)
let randnum2:Int = Int (arc4random_uniform(10) + 1)
var finVal:Int
//This function returns a random operator
func whatSign(par1:Int)-> String {
//I want to compute the variables and get final result from adding or subtracting them
if (par1 == 1){
finVal = randnum1 + randnum2
return "+"
}
else {
finVal = randnum1 - randnum2
return "-"
}
}
whatSign(par1: randsign)
print(finVal)
//When I print I get for example 1-3, 9-4, 8+2 .But I wanted them to do arithmetic
Maybe it will helps you

Swift: Cannot assign a value of type 'int' to a value of type 'int?' Error

I'm starting to learn swift, but ran into an error. Ive just created a very simple app from a course I'm following, that calculates a cats ages based on what the user enters. The first version of the app just times what the user enters by 7, which i managed todo no problem. I thought I would have a play with what I've written and change it todo this:
1st human year = 15 cat years
2nd human year = +10
3rd human year = +4
4th human year = +4
5th human year = +4
so on..
e.g. a 4 year old cat would be 33 in cat years.
So I want my results label to say You're cat is 33 in cat years
This is the code I've written:
#IBAction func findAge(sender: AnyObject) {
var enteredAge = enterAge.text.toInt()
if enteredAge = 1 {
var catYears = 15
resultLabel.text = "You're cat is \(catYears) in cat years"
} else if enteredAge = 2 {
var catYears = 25
resultLabel.text = "You're cat is \(catYears) in cat years"
} else {
var catYears = (15 + 25) + (enteredAge - 2) * 4
resultLabel.text = "You're cat is \(catYears) in cat years"
}
}
#IBOutlet weak var enterAge: UITextField!
#IBOutlet weak var resultLabel: UILabel!
This error I'm getting is on the line 17 "if enteredAge = 1 {" it states this "cannot assign a value of type 'int' to a value of type 'int?'"
I don't really understand why this value cannot be a integer, any help would be great.
The main error (as I said in a comment) is that you mixed up the assignment operator =
and the equality operator ==. The comparison should be
if enteredAge == 1 { ... }
The next problem is (as keithbhunter already stated in his answer),
toInt() returns an optional which is nil if the string is not a
valid integer, and you should use optional binding:
if let enteredAge = enterAge.text.toInt() {
// compute cat years ...
} else {
// report invalid input ...
}
Additional notes:
All your variables in that method can be declared as constants
with let.
There are 3 identical assignments resultLabel.text = ..., this can
be simplified.
Instead of if ... else if ... else you could use a switch statement.
Then your method would look like this:
if let enteredAge = enterAge.text.toInt() {
let catYears : Int
switch(enteredAge) {
case 1:
catYears = 15
case 2:
catYears = 25
default:
catYears = (15 + 25) + (enteredAge - 2) * 4
}
resultLabel.text = "You're cat is \(catYears) in cat years"
} else {
resultLabel.text = "Please enter a valid number"
}
An alternative would be to use the conditional operator ?:
(sometimes also called ternary operator):
if let enteredAge = enterAge.text.toInt() {
let catYears = enteredAge == 1 ? 15 :
enteredAge == 2 ? 25 : (15 + 25) + (enteredAge - 2) * 4
resultLabel.text = "You're cat is \(catYears) in cat years"
} else {
resultLabel.text = "Please enter a valid number"
}
I am not exactly sure of the toInt() method, but I am going to guess that method returns an Int?. This means that it can return nil if it cannot convert the string to an int. You should unwrap this value to handle nil cases.
if var enteredAge = enterAge.text.toInt() {
// the rest of the code
}
You have already assigned the value to the enteredAge variable like follows:
var enteredAge = enterAge.text.toInt()
So, you cannot do assignment on the place of this if expression. and you need to have condition on the if expression as follows.
if enteredAge == 1 {
var catYears = 15
resultLabel.text = "You're cat is \(catYears) in cat years"
}
This may help you.
should look like this :
#IBAction func button(sender: AnyObject) {
var inputYears = textField.text.toInt()!
if inputYears == 1 {
var catOld = 15
result.text = "Your cat is \(catOld) years old"
}
else if inputYears == 2 {
var catOld = 25
result.text = "Your cat is \(catOld) years old"
}
else {var catOld = (15+25) + (inputYears - 2)*4
result.text = "Your cat is \(catOld) years old"
}

How to find out if letter is Alphanumeric or Digit in Swift

I want to count the number of letters, digits and special characters in the following string:
let phrase = "The final score was 32-31!"
I tried:
for tempChar in phrase {
if (tempChar >= "a" && tempChar <= "z") {
letterCounter++
}
// etc.
but I'm getting errors. I tried all sorts of other variations on this - still getting error - such as:
could not find an overload for '<=' that accepts the supplied arguments
For Swift 5 see rustylepord's answer.
Update for Swift 3:
let letters = CharacterSet.letters
let digits = CharacterSet.decimalDigits
var letterCount = 0
var digitCount = 0
for uni in phrase.unicodeScalars {
if letters.contains(uni) {
letterCount += 1
} else if digits.contains(uni) {
digitCount += 1
}
}
(Previous answer for older Swift versions)
A possible Swift solution:
var letterCounter = 0
var digitCount = 0
let phrase = "The final score was 32-31!"
for tempChar in phrase.unicodeScalars {
if tempChar.isAlpha() {
letterCounter++
} else if tempChar.isDigit() {
digitCount++
}
}
Update: The above solution works only with characters in the ASCII character set,
i.e. it does not recognize Ä, é or ø as letters. The following alternative
solution uses NSCharacterSet from the Foundation framework, which can test characters
based on their Unicode character classes:
let letters = NSCharacterSet.letterCharacterSet()
let digits = NSCharacterSet.decimalDigitCharacterSet()
var letterCount = 0
var digitCount = 0
for uni in phrase.unicodeScalars {
if letters.longCharacterIsMember(uni.value) {
letterCount++
} else if digits.longCharacterIsMember(uni.value) {
digitCount++
}
}
Update 2: As of Xcode 6 beta 4, the first solution does not work anymore, because
the isAlpha() and related (ASCII-only) methods have been removed from Swift.
The second solution still works.
Use the values of unicodeScalars
let phrase = "The final score was 32-31!"
var letterCounter = 0, digitCounter = 0
for scalar in phrase.unicodeScalars {
let value = scalar.value
if (value >= 65 && value <= 90) || (value >= 97 && value <= 122) {++letterCounter}
if (value >= 48 && value <= 57) {++digitCounter}
}
println(letterCounter)
println(digitCounter)
For Swift 5 you can do the following for simple strings, but be vigilant about handling characters like "1️⃣" , "④" these would be treated as numbers as well.
let phrase = "The final score was 32-31!"
var numberOfDigits = 0;
var numberOfLetters = 0;
var numberOfSymbols = 0;
phrase.forEach {
if ($0.isNumber) {
numberOfDigits += 1;
}
else if ($0.isLetter) {
numberOfLetters += 1
}
else if ($0.isSymbol || $0.isPunctuation || $0.isCurrencySymbol || $0.isMathSymbol) {
numberOfSymbols += 1;
}
}
print(#"\#(numberOfDigits) || \#(numberOfLetters) || \#(numberOfSymbols)"#);
I've created a short extension for letter and digits count for a String
extension String {
var letterCount : Int {
return self.unicodeScalars.filter({ CharacterSet.letters.contains($0) }).count
}
var digitCount : Int {
return self.unicodeScalars.filter({ CharacterSet.decimalDigits.contains($0) }).count
}
}
or a function to get a count for any CharacterSet you put in
extension String {
func characterCount(for set: CharacterSet) -> Int {
return self.unicodeScalars.filter({ set.contains($0) }).count
}
}
usage:
let phrase = "the final score is 23-13!"
let letterCount = phrase.characterCount(for: .letters)
In case you only need one information (letter or number or sign) you can do it in one line:
let phrase = "The final score was 32-31!"
let count = phrase.filter{ $0.isLetter }.count
print(count) // "16\n"
But doing phrase.filter several times is inefficient because it loops through the whole string.

Resources