The compiler is unable to type-check this expression - swift

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)

Related

How can I change time format of a label ? Swift

In my App I want to show the user the Time he needed. At the moment it looks like this:
This is the actual code:
if counter <= 59.0 {
resultTimeLabel.text = String(format: "%.1", counter)
resultTimeLabel.text = "in \(counter) seconds"
}
if counter >= 60.0 {
let minutes = counter / 60.0
resultTimeLabel.text = String(format: "%.1", counter)
resultTimeLabel.text = "in \(minutes) minutes"
Which format is the right one to make it looks like: 1.5 and not 1.5000000023
The issue there is that you are assigning a new string over the previous formatted string and it is missing an "f" in your string format:
if counter < 60 {
resultTimeLabel.text = "in " + String(format: "%.1f", counter) + " seconds"
}
else
if counter >= 60 {
let minutes = counter / 60.0
resultTimeLabel.text = "in " + String(format: "%.1f", minutes) + " minutes"

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
}
*
* *
* *
* *
*********

Subtracting inputed data in 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.

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

Format println output in a table

Like this Java question, but for Swift.
How can I output a table like this to the console, ideally using println?
n result1 result2 time1 time2
-----------------------------------------------------
5 1000.00 20000.0 1000ms 1250ms
5 1000.00 20000.0 1000ms 1250ms
5 1000.00 20000.0 1000ms 1250ms
I tried using println("n\tresult1\tresult2") but the results don't line up properly.
I found a quick and easy way to generate columnar text output in Swift (3.0) using the String method "padding(::)" [In Swift 2.x, the method is named "stringByPaddingToLength(::)"]. It allows you to specify the width of your column, the text you want to use as a pad, and the index of the pad to start with. Works like a charm if you don't mind that it only works with left-aligned text columns. If you want other alignments, you have to buy into the other methods of character counting and other such complexities.
The solution below is contrived to illustrate the utility of the method "padding(::)". Obviously, the best way to leverage this would be to create a function that iterated through a collection to produce the desired table while minimizing code repetition. I did it this way to focus on the task at hand.
Lastly, "println" doesn't seem to exist in Swift 2.x+, so I reverted to "print()".
To illustrate an example using your stated problem:
//Set up the data
let n : Int = 5
let result1 = 1000.0
let result2 = 20000.0
let time1 = "1000ms"
let time2 = "1250ms"
//Establish column widths
let column1PadLength = 8
let columnDefaultPadLength = 12
//Define the header string
let headerString = "n".padding(toLength: column1PadLength, withPad: " ", startingAt: 0) + "result1".padding(toLength: columnDefaultPadLength, withPad: " ", startingAt: 0) + "result2".padding(toLength: columnDefaultPadLength, withPad: " ", startingAt: 0) + "time1".padding(toLength: columnDefaultPadLength, withPad: " ", startingAt: 0) + "time2".padding(toLength: columnDefaultPadLength, withPad: " ", startingAt: 0)
//Define the line separator
let lineString = "".padding(toLength: headerString.characters.count, withPad: "-", startingAt: 0)
//Define the string to display a line of our data
let nString = String(n)
let result1String = String(result1)
let result2String = String(result2)
let dataString = nString.padding(toLength: column1PadLength, withPad: " ", startingAt: 0) + result1String.padding(toLength: columnDefaultPadLength, withPad: " ", startingAt: 0) + result2String.padding(toLength: columnDefaultPadLength, withPad: " ", startingAt: 0) + time1.padding(toLength: columnDefaultPadLength, withPad: " ", startingAt: 0) + time2.padding(toLength: columnDefaultPadLength, withPad: " ", startingAt: 0)
//Print out the data table
print("\(headerString)\n\(lineString)\n\(dataString)")
The output will be printed to your console in a tidy columnar format:
n result1 result2 time1 time2
--------------------------------------------------------
5 1000.0 20000.0 1000ms 1250ms
Changing the variable "columnDefaultPadLength" from 12 to 8 will result in the following output:
n result1 result2 time1 time2
----------------------------------------
5 1000.0 20000.0 1000ms 1250ms
Finally, reducing the padding length to a value less than the data truncates the data instead of generating errors, very handy! Changing the "columnDefaultPadLength" from 8 to 4 results in this output:
n resuresutimetime
------------------------
5 1000200010001250
Obviously not a desired format, but with the simple adjustment of the padding length, you can quickly tweak the table into a compact yet readable form.
You need to determine the maximum length of a string in your data (from both the keys and values) and then pad those strings. You can use a function like what I've provided below to calculate the maximum length and go from there.
func maxLength(data: Dictionary<String,Double>) -> Int {
var greatestLength = 0
for (key, value) in data {
var valueLength = countElements(String(format: "%.2f", value))
var keyLength = countElements(key)
var length = max(valueLength, keyLength)
if (length > greatestLength) {
greatestLength = length
}
}
return greatestLength
}