How can I covert this to swift? My best guess is that all the int get changed to a var. Removing all the @ that lead ". Also if any can point me to a good source to learn how things convert that would great.
- (NSString*)coordinateString {
int latSeconds = (int)(self.latitude * 3600);
int latDegrees = latSeconds / 3600;
latSeconds = ABS(latSeconds % 3600);
int latMinutes = latSeconds / 60;
latSeconds %= 60;
int longSeconds = (int)(self.longitude * 3600);
int longDegrees = longSeconds / 3600;
longSeconds = ABS(longSeconds % 3600);
int longMinutes = longSeconds / 60;
longSeconds %= 60;
NSString* result = [NSString stringWithFormat:@"%d°%d'%d\"%@ %d°%d'%d\"%@",
ABS(latDegrees),
latMinutes,
latSeconds,
latDegrees >= 0 ? @"N" : @"S",
ABS(longDegrees),
longMinutes,
longSeconds,
longDegrees >= 0 ? @"E" : @"W"];
return result;
}
My attempt to convert it but Xcode proves me wrong. Reposted the fix suggest with the ABS. Does it look correct now?
func coordinateString {
var latSeconds = (Int8)(self.latitude * 3600);
var latDegrees = latSeconds / 3600;
latSeconds = abs(latSeconds % 3600);
var latMinutes = latSeconds / 60;
latSeconds %= 60;
var longSeconds = (Int8)(self.longitude * 3600);
var longDegrees = longSeconds / 3600;
longSeconds = abs(longSeconds % 3600);
var longMinutes = longSeconds / 60;
longSeconds %= 60;
var result = (String(format: "%d°%d'%d\"%@ %d°%d'%d\"%@"),
abs(latDegrees),
latMinutes,
latSeconds,
latDegrees >= 0 ? "N" : "S",
abs(longDegrees),
longMinutes,
longSeconds,
longDegrees >= 0 ? "E" : "W",
return result;
}
I took the code of Leo Dabus and fixed a bug related with the detection of the cardinal directions when the values of the latitude or longitude are less than zero, I mean when we are at southern hemisphere or west of the prime meridian.
We can't represent a negative zero with Swift, so we lose the negative sign at the following expression:
this bug also makes the expresion:
always return N (North) and never S (South).
Here is my version of the code (Swift 5 and Xcode 10):
I also chose to work with Double in order to handle the precision, for example, I prefer to show two decimal places.
The screen output of this code would be something like:
Based on David Seek and Josué V. Herrera code
Call to it with
I have just edited Leo Dabus answer to get those String as separate values. In case it is helpful for others:
Swift 3 and Swift 4
I slightly modified Josue V.'s code to work in a timer that updates the location frequently
and the timer
timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(coordinate), userInfo: nil, repeats: true)
Xcode 8.3.2 • Swift 3.1