Last active
January 18, 2017 09:15
-
-
Save chreke/352ceabccfb621105c8fd49adbff25c5 to your computer and use it in GitHub Desktop.
Some Swift code examples
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// A constant Int | |
let meaningOfLife = 42 | |
// A variable String | |
var greeting = "Hello!" | |
// Type inference on enum members | |
var directionToHead = CompassPoint.west | |
directionToHead = .east | |
var maybeString: String? | |
var maybeAnotherString: String? | |
maybeString = "hej" | |
// Optional binding | |
if let aString = maybeString { | |
print("This is a string: \(aString)") | |
} | |
// Optional chaining | |
let count: Int? = maybeAnotherString?.characters.count | |
let point = (9, 0) | |
switch point { | |
case (let distance, 0), (0, let distance): | |
print("On an axis, \(distance) from the origin") | |
default: | |
print("Not on an axis") | |
} | |
enum Flavor { | |
.vanilla | |
.chocolate | |
.strawberry | |
} | |
enum ASCIIControlCharacter: Character { | |
case tab = "\t" | |
case lineFeed = "\n" | |
case carriageReturn = "\r" | |
} | |
// Sum type | |
enum Result<T> { | |
.error(Error) | |
.result(T) | |
} | |
let result = Result.success("👍") | |
// Recursive | |
enum ArithmeticExpression { | |
case number(Int) | |
indirect case addition(ArithmeticExpression, ArithmeticExpression) | |
indirect case multiplication(ArithmeticExpression, ArithmeticExpression) | |
} | |
// Obj-C style | |
asyncFunction() { | |
value, error in | |
if error == nil { | |
assert(value == nil) | |
// Handle error | |
return | |
} | |
assert(value != nil) | |
// Do something with value | |
} | |
asyncFunction() { | |
result in | |
switch result { | |
case let .error(error): | |
// Handle errors | |
case let .success(value): | |
// Do something with value | |
} | |
} | |
// Protocols | |
protocol YamlSerializable { | |
func toYaml() -> String | |
} | |
extension Date: YamlSerializable { | |
func toYaml() -> String { | |
return ISO8601DateFormatter().string(from: self) | |
} | |
} | |
["foo", "", "bar"].filter(.isEmpty) | |
extension Collection where Iterator.Element: YamlSerializable { | |
var textualDescription: String { | |
let itemsAsText = self.map { $0.textualDescription } | |
return "[" + itemsAsText.joined(separator: ", ") + "]" | |
} | |
} | |
func foo() { | |
var foobar = [[1, 2], [3, 4], [5]] | |
var bar = foobar[0] | |
bar[0] = [10] | |
return foobar | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment