Skip to content

Instantly share code, notes, and snippets.

@bryantjustin
Last active August 29, 2015 14:02
Show Gist options
  • Save bryantjustin/a1e41793994e07452e77 to your computer and use it in GitHub Desktop.
Save bryantjustin/a1e41793994e07452e77 to your computer and use it in GitHub Desktop.
Taking Swift for a Test Flight
// As a local variable:
NSString*(^foo)(NSString *bar) = ^NSString*(NSString *bar) {
return [NSString stringWithFormat: @"Hello %@", bar];
};
// As a property:
@property (nonatomic, copy) NSString*(^foo)(NSString *bar);
// As a method parameter:
- (void)takeBlock:(NSString*(^)(NSString *bar))foo;
// As an argument to a method call:
[self takeBlock:
^NSString*(NString *bar) {
return [NSString stringWithFormat: @"Hello %@", bar]
}
];
// As a typedef:
typedef NSString*(^Foo)(NSString *bar);
Foo foo = ^NSString*(NSString *bar) {
return [NSString stringWithFormat: @"Hello %@", bar];
};
// For loop that prints "Hello World" 20 times.
for (int = 0; i < 20; i++)
{
NSLog( @"Hello World" );
}
// For loop that prints "Hello World" 21 times.
for (int = 0; i <= 20; i++)
{
NSLog( @"Hello World" );
}
// As a local variable:
var foo = { (bar: String) -> String in
return "Hello " + bar
}
// As a constant and as a property:
let baz = { (bar: String) -> String in
return "Hello " + bar
}
var foo: String -> String = {
get { return baz }
set { baz = newValue; }
}
// As a method parameter
func takeClosure( foo: String -> String )
// As an argument to a method call:
takeClosure({ (bar: String) -> String in
return "Hello " + bar
})
// As a typealias (typedef equivalent):
typealias Foo = String -> String
var foo: Foo = { (bar: String) -> String in
return "Hello " + bar
}
// For loop that prints "Hello World" 20 times.
for i in 0..20
{
println( "Hello World" );
}
// For loop that prints "Hello World" 21 times.
for i in 0...20
{
println( "Hello World" );
}
let hello = "Hello"
let world = "World"
// Prints "Hello World"
println( "\(hello) \(world)" )
class Foo {
@lazy var bar = Bar();
}
let foo = Foo();
// On initialization of foo, foo.bar is not yet initialized.
foo.bar.baz()
// bar is now initialized when the baz property is accessed.
// Function declaration where the external parameter is the same as the internal parameter
func compare(string1 string1: String, string2 string2: String) -> Bool
// The previous function can be shortened using (#)
func compare(#string1: String, #string2: String) -> Bool
// Declaring a tuple.
let foo = ("Hello", "World", 1.0 );
// Declaration for a function that returns a tuple
func returnATuple() -> (String, String, Float) {
return foo;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment