summaryrefslogtreecommitdiffhomepage
diff options
context:
space:
mode:
authorC. Bess <cbess@quantumquinn.com>2014-08-24 00:48:54 -0500
committerC. Bess <cbess@quantumquinn.com>2014-08-24 00:48:54 -0500
commit6b34ef65a3aea7af638145be83c1d3699caa353b (patch)
treea5097c81a81b8b2d2469061647dd5f3fcf9b74c9
parent328a4f1babe167e94858b92faaa9caa19aa8aade (diff)
- more examples
- add custom operator example
-rw-r--r--swift.html.markdown54
1 files changed, 50 insertions, 4 deletions
diff --git a/swift.html.markdown b/swift.html.markdown
index 5ba160b8..6ce60cf5 100644
--- a/swift.html.markdown
+++ b/swift.html.markdown
@@ -26,9 +26,9 @@ let `class` = "keyword" // backticks allow keywords to be used as variable names
let explicitDouble: Double = 70
let intValue = 0007 // 7
let largeIntValue = 77_000 // 77000
-let label = "some text " + String(myVariable) // Casting
-let piText = "Pi = \(myConstant)" // String interpolation
-var optionalString: String? = "optional" // Can be nil
+let label = "some text " + String(myVariable) // Casting
+let piText = "Pi = \(myConstant), Pi 2 = \(myConstant * 2)" // String interpolation
+var optionalString: String? = "optional" // Can be nil
optionalString = nil
/*
@@ -114,7 +114,17 @@ default: // required (in order to cover all possible input)
// Functions are a first-class type, meaning they can be nested
// in functions and can be passed around
-// Function
+// Function with Swift docs
+/**
+ A greet operation
+
+ - A bullet in docs
+ - Another bullet in the docs
+
+ :param: name A name
+ :param: day A day
+ :returns: A string containing the name and day value.
+*/
func greet(name: String, day: String) -> String {
return "Hello \(name), today is \(day)."
}
@@ -237,6 +247,11 @@ print(mySquare.getArea()) // 25
mySquare.shrink()
print(mySquare.sideLength) // 4
+// compare instances, not the same as == which compares objects (equal to)
+if mySquare === mySquare {
+ println("Yep its mySquare")
+}
+
//
// MARK: Enums
@@ -276,6 +291,20 @@ extension Square: Printable {
println("Square: \(mySquare)")
+// You can also extend built-in types
+extension Int {
+ var customProperty: String {
+ return "This is \(self)"
+ }
+
+ func multiplyBy(num: Int) -> Int {
+ return num * self
+ }
+}
+
+println(7.customProperty) // "This is 7"
+println(14.multiplyBy(2)) // 42
+
// Generics: Similar to Java. Use the `where` keyword to specify the
// requirements of the generics.
@@ -288,4 +317,21 @@ func findIndex<T: Equatable>(array: [T], valueToFind: T) -> Int? {
return nil
}
+
+// Operators:
+// Custom operators can start with the characters:
+// / = - + * % < > ! & | ^ . ~
+// or
+// Unicode math, symbol, arrow, dingbat, and line/box drawing characters.
+prefix operator !!! {}
+
+// An operator that triples the side length when used
+prefix func !!! (inout shape: Square) -> Square {
+ shape.sideLength *= 3
+ return shape
+}
+
+let bigSquare = !!!mySquare
+println(bigSquare.sideLength)
+
```