by
8,516 33
1
6
3,479
0
Top 1% !
Popular
Famous
Easy-to-find
Specified
Pattern
Popularity: 3751st place
BrowserChrome
LanguageObjectiveC
LanguageSwift
LicenseMIT_X11

Swift Collections: Simple function with return value

I want to our function to get the current time, formatted and returned as a String.
Copy Embed Code
<iframe id="embedFrame" style="width:600px; height:300px;"
src="https://www.snip2code.com/Embed/121750/Swift-Collections--Simple-function-with-?startLine=0"></iframe>
Click on the embed code to copy it into your clipboard Width Height
Leave empty to retrieve all the content Start End
=> Objective-C: -(NSString *)getCurrentTime { NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setTimeStyle:NSDateFormatterShortStyle]; NSString *currentTime = [dateFormatter stringFromDate:[NSDate date]]; return currentTime; } To call this method within the same class: NSString *time = [self getCurrentTime]; NSLog(@"%@",time); //Results in the getCurrentTime function being called and the current time printed to the console. => Swift In Swift, we include the return arrow “->” which specifies that the function will return and the type of object that will be returned (String). func getCurrentTime() -> String { let date = NSDate() let formatter = NSDateFormatter() formatter.timeStyle = .ShortStyle var stringValue = formatter.stringFromDate(date) return stringValue } To call this method within the same class: let time = getCurrentTime() println(time) //Results in the getCurrentTime function being called and the current time printed to the console.
If you want to be updated about similar snippets, Sign in and follow our Channels

blog comments powered by Disqus