Subtracting inputed data in Swift - swift

Good afternoon,
I am having an issue trying to figure out how I take data that was inputed from a textfield and use that data later on in the code. I have attached my code and hopefully I would be able to get some help.
#IBAction func wEnter(sender: AnyObject) {
let number1 = Double(waistText1?.text ?? "") ?? 0
let number2 = Double(waistText2?.text ?? "") ?? 0
let number3 = Double(waistText3?.text ?? "") ?? 0
let number4 = Double(neckText1?.text ?? "") ?? 0
let number5 = Double(neckText2?.text ?? "") ?? 0
let number6 = Double(neckText3?.text ?? "") ?? 0
wavgText.text = String(round(10 * (number1 + number2 + number3) / 3) / 10 ) + " inches"
navgText.text = String((number4 + number5 + number6) / 3) + " inches"
let number7 = Double(wavgText.text! )
let number8 = Double(navgText.text! )
soldBF.text = String(number7 - number8) + "%"
}
Everything seems to be working correctly except for when i try to subtract number7 from number 8. Am i missing something?
if you need anymore details please let me know

It will be better if you switch the order of operations:
let number7 = round(10 * (number1 + number2 + number3) / 3) / 10
let number8 = (number4 + number5 + number6) / 3
wavgText.text = "\(number7) inches"
navgText.text = "\(number8) inches"
soldBF.text = "\(number7 - number8)%"
Then you can see what the problem is.

Related

The compiler is unable to type-check this expression

I want to divide difference data into 60 and print it as double numbers. When I print it as a string, it does not appear to be a fraction of the number. I get this problem when I print the number "n" . What should I do?
My mistake: the compiler is unable to type-check this expression in reasonable time; try breaking up the expression into distinct sub-expressions
if let date = formatter.date(from: receivedTimeString) {
let receivedTimeHoursMinutes = Calendar.current.component(.hour, from: date) * 60
let receivedTimeMinutes = Calendar.current.component(.minute, from: date)
let totalreceivedTimeMinutes = receivedTimeHoursMinutes + receivedTimeMinutes
let todayHoursMinutes = Calendar.current.component(.hour, from: Date()) * 60
let todayMinutes = Calendar.current.component(.minute, from: Date())
let todayTimeMinutes = todayHoursMinutes + todayMinutes
let difference = todayTimeMinutes - totalreceivedTimeMinutes
let str = String(difference)
switch true {
case difference > 60:
let deger = String(difference / 60)
guard let n = NumberFormatter().number(from: deger) else { return }
print("deger", deger)
self.labelTimerFarkSonuc.text = (n) + (" ") + ("Saattir") + (" ") + (durum)
case difference == 0:
self.labelTimerFarkSonuc.text = (n) + (" ") + ("Dakikadır") + (" ") + (durum)
case difference < 60:
self.labelTimerFarkSonuc.text = (n) + (" ") + ("Dakikadır") + (" ") + (durum)
default:
self.labelTimerFarkSonuc.text = (n) + (" ") + ("Dakikadır") + (" ") + (durum)
}
If i had understood your question correctly,
If you want to have result of following code as decimal fraction,
let deger = String(difference / 60) // Dividing by INT will not give fractions.
Change it to following.
let deger = String(difference / 60.0)

trying to make an asterisk triangle in Swift using a while loop

I'm trying to make tan asterisk triangle output in Swift. I HAVE to use a while loop.
I have tried doing a while loop by it's self - no luck
I think I need to nest a while loop with a for loop but not even sure I can do that. Or I may be making this way harder than it needs to be :). Super new to programming...I simply do not know how to add an"*" in the while loop. below is the latest code that I have tried but it's wrong(obviously) any help would be appreciated
let rows = 5
for i in 1...rows{
for j in 1...i{
print("\(j) ", terminator: "")
}
var num_stars = 1
while num_stars <= 5{
print(num_stars)
num_stars += 1
}
print("")
}
Simply :
let rows = 5
var i = 1
while i <= rows {
print(String(repeating: "*", count: i))
i += 1
}
which outputs :
*
**
***
****
*****
This looks prettier to me :
let rows = 5
var i = 0
while i < rows {
let spaces = String(repeating: " ", count: rows - i - 1)
let stars = String(repeating: "*", count: 2 * i + 1)
print(spaces + stars)
i += 1
}
*
***
*****
*******
*********
Or :
while i < rows {
let spaces = String(repeating: " ", count: rows - i - 1)
print(spaces, terminator: "")
if i > 0 {
print("*", terminator: "")
if i < rows - 1 {
let insideTriangleSpaces = String(repeating: " ", count: 2 * (i - 1) + 1)
print(insideTriangleSpaces, terminator: "")
} else {
let insideTriangleStars = String(repeating: "*", count: 2 * (i - 1) + 1)
print(insideTriangleStars, terminator: "")
}
}
print("*")
i += 1
}
*
* *
* *
* *
*********

Swift 4, how to remove two nth charterers from sentence, and start counting each letter in sentence from 1 instead of 0

I've come outwith this code to remove two charahcters from sentence, however I was wondering how to start counting sentence from 1 when removing characters.
Examplre user enters in each textfield as following:
textfield.text: Hi, thankyou
inputlabelOne.text: 2
inputLabelTwo.text: 5
My code:
var numberOne = Int (InputLabelOne.text)!
var numberTwo = Int (InputLabelTwo.text)!
var text = textfield.text!
var num1 = numberOne
var num2 = numberTwo
if let oneIndex = text.index ((text.startIndex), offsetBy:
num1, limetedBy:(text.endIndex)) ,
let twoIndex = text.index ((text.startIndex), offsetBy: num2,
limetedBy:(text.endIndex)) {
text.remove(at: oneIndex)
text.remove(at: twoIndex)
outputLabel.Text = "sentence with removed letters: \(text)"
}
Firstly, you need to get first index of the string
let startIndex = string.startIndex
Next, you need to get String.Index of the character at first position
let index1 = string.index(startIndex, offsetBy: num1 - 1)
I type minus one because first character has 0 index
Next, you can remove this character
str.remove(at: index1)
Same for the second character
let offset = num1 > num2 ? 1 : 2
let index2 = string.index(startIndex, offsetBy: num2 - offset)
str.remove(at: index2)
If num1 is less than num2 then offset value is 2 because we have already removed one character.
If num1 is greater than num2 then offset value is 1 as for num1.
To avoid the mutating while iterating mistake you have to remove the characters backwards starting at the highest index.
To get 1-based indices just subtract 1 from the offset respectively
var text = "Hi, thankyou"
let inputLabelOne = 2
let inputLabelTwo = 5
if let oneIndex = text.index(text.startIndex, offsetBy: inputLabelOne - 1, limitedBy: text.endIndex),
let twoIndex = text.index(text.startIndex, offsetBy: inputLabelTwo - 1, limitedBy: text.endIndex) {
text.remove(at: twoIndex)
text.remove(at: oneIndex)
}
print(text) // H, hankyou
or as function
func remove(at indices: [Int], from text: inout String) {
let sortedIndices = indices.sorted(by: >)
for index in sortedIndices {
if let anIndex = text.index(text.startIndex, offsetBy: index - 1, limitedBy: text.endIndex) {
text.remove(at: anIndex)
}
}
}
remove(at: [inputLabelOne, inputLabelTwo], from: &text)

Splitting a UInt16 to 2 UInt8 bytes and getting the hexa string of both. Swift

I need 16383 to be converted to 7F7F but I can only get this to be converted to 3fff or 77377.
I can convert 8192 to hexadecimal string 4000 which is essentially the same thing.
If I use let firstHexa = String(format:"%02X", a) It stops at 3fff hexadecimal for the first number and and 2000 hexadecimal for the second number. here is my code
public func intToHexString(_ int: Int16) -> String {
var encodedHexa: String = ""
if int >= -8192 && int <= 8191 {
let int16 = int + 8192
//convert to two unsigned Int8 bytes
let a = UInt8(int16 >> 8 & 0x00ff)
let b = UInt8(int16 & 0x00ff)
//convert the 2 bytes to hexadecimals
let first1Hexa = String(a, radix: 8 )
let second2Hexa = String(b, radix: 8)
let firstHexa = String(format:"%02X", a)
let secondHexa = String(format:"%02X", b)
//combine the 2 hexas into 1 string with 4 characters...adding 0 to the beggining if only 1 character.
if firstHexa.count == 1 {
let appendedFHexa = "0" + firstHexa
encodedHexa = appendedFHexa + secondHexa
} else if secondHexa.count == 1 {
let appendedSHexa = "0" + secondHexa
encodedHexa = firstHexa + appendedSHexa
} else {
encodedHexa = firstHexa + secondHexa
}
}
return encodedHexa
}
Please help ma'ams and sirs! Thanks.
From your test cases, it seems like your values are 7 bits per byte.
You want 8192 to convert to 4000.
You want 16383 to convert to 7F7F.
Note that:
(0x7f << 7) + 0x7f == 16383
Given that:
let a = UInt8((int16 >> 7) & 0x7f)
let b = UInt8(int16 & 0x7f)
let result = String(format: "%02X%02X", a , b)
This gives:
"4000" for 8128
"7F7F" for 16383
To reverse the process:
let str = "7F7F"
let value = Int(str, radix: 16)!
let result = ((value >> 8) & 0x7f) << 7 + (value & 0x7f)
print(result) // 16383

Basic Adding - Expression was too complex error (Swift)

Trying to add some simple numbers together. Get the "Expression was too complex to be solved in a reasonable time..." error on the final line. Why? Surely it can't come much simpler?
let year = calendar.component(.CalendarUnitYear, fromDate: inputGregorianDate)
let month = calendar.component(.CalendarUnitMonth, fromDate: inputGregorianDate)
let day = calendar.component(.CalendarUnitDay, fromDate: inputGregorianDate)
// Conversion Calulation
let AGR = year/100
let BGR = AGR/4
let CGR = 2 - AGR + BGR
var EGR = 0.00
if (month <= 2 ) {
EGR = 365.25 * Double(year + 4716)
} else {
EGR = 365.25 * Double(year + 4716);
}
let FGR = 30.6001 * Double(month + 1);
let dateJulian = Double(CGR + day + EGR + FGR - 1524.5)
// Conversion Calulation
let AGR = Double(year) / 100
let BGR = AGR / 4.0
let CGR = 2.0 - AGR + BGR
var EGR = 0.0
// this conditional doesn't make any sense
if (month <= 2 ) {
EGR = 365.25 * Double(year + 4716)
} else {
EGR = 365.25 * Double(year + 4716)
}
let FGR = 30.6001 * Double(month + 1)
let dateJulian = CGR + Double(day) + EGR + FGR - 1524.5