Closures:
The use of variables the hold a function vs. using a function itself can help:
65 bytes:
var r:(String,Int)->String={return String(repeating:$0,count:$1)}
66 bytes:
func r(s:String,i:Int)->String{return String(repeating:s,count:i)}
Small difference here, but it'll show more in some puzzles.
Shortening Functions:
Looking at the previous example reminds me of something. Sometimes, if you will be using a function enough times, it is worth the space to rename it:
This:
String(repeating:$0,count:$1)
To this:
var r:(String,Int)->String={return String(repeating:$0,count:$1)}
Or, actually, this is better:
var r=String.init(repeating:count:)
That way you just call r("Hello World",8)
instead of String(repeating:"Hello World",count:8)
Leaving Out Type Declarations:
I once created a closure without setting the argument type, thus creating a shorter answer:
var f={(i)->Int in i-1+i%2*2}
The compiler inferred that i
is in Int
.
Create Arrays the Fast Way:
If you need an array of Ints
, use a Range
to create it:
Array(0...5)
This does the same thing as:
[0,1,2,3,4,5]
Arrays Instead of If
or Switch
:
Instead of doing this:
if n==0{return "a"}else if n==1{return "b"}else{return "c"}
You can probably do this:
return ["a","b","c"][n]
Shorten Types:
If you are using type conversion a lot, you might want to create a type alias:
typealias f=Float
Map:
Remember that you often don't need to use the return
keyword in the map
function.
Running Swift Online:
Although Try It Online does not support Swift It does now!