From 328a4f1babe167e94858b92faaa9caa19aa8aade Mon Sep 17 00:00:00 2001 From: "C. Bess" Date: Sat, 23 Aug 2014 22:48:10 -0500 Subject: - add more examples; update examples - now runs in the Xcode 6 b6 playground - add MARK sections --- swift.html.markdown | 206 ++++++++++++++++++++++++++++++++++------------------ 1 file changed, 135 insertions(+), 71 deletions(-) (limited to 'swift.html.markdown') diff --git a/swift.html.markdown b/swift.html.markdown index a47b085a..5ba160b8 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -2,6 +2,7 @@ language: swift contributors: - ["Grant Timmerman", "http://github.com/grant"] + - ["Christopher Bess", "http://github.com/cbess"] filename: learnswift.swift --- @@ -11,21 +12,34 @@ See also Apple's [getting started guide](https://developer.apple.com/library/pre ```js // -// Basics +// MARK: Basics // println("Hello, world") + var myVariable = 42 +//let fƒ∆ = "value" // unicode in variable names let myConstant = 3.1415926 +let convenience = "keyword" // contextual variable name +let weak = "keyword"; let override = "another keyword" // statements can be separated by a semi-colon +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 optionalString = nil +/* +Comment here + /* + Nested comment here + */ +*/ // -// Arrays and Dictionaries +// MARK: Collections // // Array @@ -35,65 +49,66 @@ let emptyArray = [String]() // Dictionary var occupations = [ - "Malcolm": "Captain", - "kaylee": "Mechanic" + "Malcolm": "Captain", + "kaylee": "Mechanic" ] occupations["Jayne"] = "Public Relations" let emptyDictionary = Dictionary() // -// Control Flow +// MARK: Control Flow // // for loop (array) let myArray = [1, 1, 2, 3, 5] for value in myArray { - if value == 1 { - println("One!") - } else { - println("Not one!") - } + if value == 1 { + println("One!") + } else { + println("Not one!") + } } // for loop (dictionary) +var dict = ["one": 1, "two": 2] for (key, value) in dict { - println("\(key): \(value)") + println("\(key): \(value)") } // for loop (range) for i in -1...1 { // [-1, 0, 1] - println(i) + println(i) } // use ..< to exclude the last number // while loop var i = 1 while i < 1000 { - i *= 2 + i *= 2 } // do-while loop do { - println("hello") + println("hello") } while 1 == 2 // Switch let vegetable = "red pepper" switch vegetable { case "celery": - let vegetableComment = "Add some raisins and make ants on a log." + let vegetableComment = "Add some raisins and make ants on a log." case "cucumber", "watercress": - let vegetableComment = "That would make a good tea sandwich." + let vegetableComment = "That would make a good tea sandwich." case let x where x.hasSuffix("pepper"): - let vegetableComment = "Is it a spicy \(x)?" + let vegetableComment = "Is it a spicy \(x)?" default: // required (in order to cover all possible input) - let vegetableComment = "Everything tastes good in soup." + let vegetableComment = "Everything tastes good in soup." } // -// Functions +// MARK: Functions // // Functions are a first-class type, meaning they can be nested @@ -101,31 +116,31 @@ default: // required (in order to cover all possible input) // Function func greet(name: String, day: String) -> String { - return "Hello \(name), today is \(day)." + return "Hello \(name), today is \(day)." } greet("Bob", "Tuesday") // Function that returns multiple items in a tuple func getGasPrices() -> (Double, Double, Double) { - return (3.59, 3.69, 3.79) + return (3.59, 3.69, 3.79) } -// Args +// Variadic Args func setup(numbers: Int...) {} // Passing and returning functions func makeIncrementer() -> (Int -> Int) { - func addOne(number: Int) -> Int { - return 1 + number - } - return addOne + func addOne(number: Int) -> Int { + return 1 + number + } + return addOne } var increment = makeIncrementer() increment(7) // -// Closures +// MARK: Closures // var numbers = [1, 2, 6] @@ -135,93 +150,142 @@ var numbers = [1, 2, 6] // `->` separates the arguments and return type // `in` separates the closure header from the closure body numbers.map({ - (number: Int) -> Int in - let result = 3 * number - return result - }) + (number: Int) -> Int in + let result = 3 * number + return result +}) // When the type is known, like above, we can do this numbers = numbers.map({ number in 3 * number }) -//Or even this +// Or even this //numbers = numbers.map({ $0 * 3 }) print(numbers) // [3, 6, 18] +// Trailing closure +numbers = sorted(numbers) { $0 > $1 } + +print(numbers) // [18, 6, 3] + +// Super shorthand, since the < operator infers the types + +numbers = sorted(numbers, < ) + +print(numbers) // [3, 6, 18] // -// Classes +// MARK: Classes // +class Shape { + func getArea() -> Int { + return 0; + } +} + // All methods and properties of a class are public. // If you just need to store data in a // structured object, you should use a `struct` // A simple class `Square` extends `Shape` class Rect: Shape { - var sideLength: Int = 1 - - // Custom getter and setter property - var perimeter: Int { - get { - return 4 * sideLength + var sideLength: Int = 1 + + // Custom getter and setter property + var perimeter: Int { + get { + return 4 * sideLength + } + set { + sideLength = newValue / 4 + } } - set { - sideLength = newValue / 4 + + // If you don't need a custom getter and setter, + // but still want to run code before and after getting or setting + // a property, you can use `willSet` and `didSet` + var identifier: String = "defaultID" { + willSet(someIdentifier) { + print(someIdentifier) + } } - } - - init(sideLength: Int) { - super.init() - self.sideLength = sideLength - } - - func shrink() { - if sideLength > 0 { - --sideLength + + init(sideLength: Int) { + super.init() + self.sideLength = sideLength + } + + func shrink() { + if sideLength > 0 { + --sideLength + } } - } + + override func getArea() -> Int { + return sideLength * sideLength + } +} - override func getArea() -> Int { - return sideLength * sideLength - } +class Square: Rect { + convenience init() { + self.init(sideLength: 5) + } } -var mySquare = new Square(sideLength: 5) + +var mySquare = Square() print(mySquare.getArea()) // 25 mySquare.shrink() print(mySquare.sideLength) // 4 -// If you don't need a custom getter and setter, -// but still want to run code before and after getting or setting -// a property, you can use `willSet` and `didSet` - // -// Enums +// MARK: Enums // // Enums can optionally be of a specific type or on their own. // They can contain methods like classes. enum Suit { - case Spades, Hearts, Diamonds, Clubs - func getIcon() -> String { - switch self { - case .Spades: return "♤" - case .Hearts: return "♡" - case .Diamonds: return "♢" - case .Clubs: return "♧" + case Spades, Hearts, Diamonds, Clubs + func getIcon() -> String { + switch self { + case .Spades: return "♤" + case .Hearts: return "♡" + case .Diamonds: return "♢" + case .Clubs: return "♧" + } } - } } // -// Other +// MARK: Other // // `protocol`: Similar to Java interfaces. -// `extension`s: Add extra functionality to an already created type +protocol ShapeGenerator { + func buildShape() -> Shape +} + +// `extension`s: Add extra functionality to an already existing type +extension Square: Printable { + var description: String { + return "Area: \(self.getArea()) - ID: \(self.identifier)" + } +} + +println("Square: \(mySquare)") + // Generics: Similar to Java. Use the `where` keyword to specify the // requirements of the generics. +func findIndex(array: [T], valueToFind: T) -> Int? { + for (index, value) in enumerate(array) { + if value == valueToFind { + return index + } + } + return nil +} + ``` -- cgit v1.2.3 From 6b34ef65a3aea7af638145be83c1d3699caa353b Mon Sep 17 00:00:00 2001 From: "C. Bess" Date: Sun, 24 Aug 2014 00:48:54 -0500 Subject: - more examples - add custom operator example --- swift.html.markdown | 54 +++++++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 50 insertions(+), 4 deletions(-) (limited to 'swift.html.markdown') 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(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) + ``` -- cgit v1.2.3 From 2a5a4ebf64593009002053514deb057f37d7b693 Mon Sep 17 00:00:00 2001 From: "C. Bess" Date: Sun, 24 Aug 2014 14:37:09 -0500 Subject: - add landmark notes --- swift.html.markdown | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) (limited to 'swift.html.markdown') diff --git a/swift.html.markdown b/swift.html.markdown index 6ce60cf5..600eedcf 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -15,6 +15,11 @@ See also Apple's [getting started guide](https://developer.apple.com/library/pre // MARK: Basics // +// Xcode supports landmarks to annotate your code and lists them in the jump bar +// MARK: Section mark +// TODO: Do something soon +// FIXME Fix this code + println("Hello, world") var myVariable = 42 @@ -114,7 +119,7 @@ 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 with Swift docs +// Function with Swift function docs /** A greet operation -- cgit v1.2.3 From b50d4443cdca87e3342e2364c9e6afd2d7fce7d2 Mon Sep 17 00:00:00 2001 From: "C. Bess" Date: Sun, 24 Aug 2014 18:33:16 -0500 Subject: - add more examples; add book link - add link to official Swift book from Apple - add examples of access control and structures - update protocols --- swift.html.markdown | 95 +++++++++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 81 insertions(+), 14 deletions(-) (limited to 'swift.html.markdown') diff --git a/swift.html.markdown b/swift.html.markdown index 600eedcf..f8fa31fe 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -8,6 +8,8 @@ filename: learnswift.swift Swift is a programming language for iOS and OS X development created by Apple. Designed to coexist with Objective-C and to be more resilient against erroneous code, Swift was introduced in 2014 at Apple's developer conference WWDC. It is built with the LLVM compiler included in Xcode 6 beta. +The official [Swift Programming Language](https://itunes.apple.com/us/book/swift-programming-language/id881256329) book from Apple is now available via iBooks. + See also Apple's [getting started guide](https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/LandingPage/index.html), which has a complete tutorial on Swift. ```js @@ -23,7 +25,7 @@ See also Apple's [getting started guide](https://developer.apple.com/library/pre println("Hello, world") var myVariable = 42 -//let fƒ∆ = "value" // unicode in variable names +let øπΩ = "value" // unicode variable names let myConstant = 3.1415926 let convenience = "keyword" // contextual variable name let weak = "keyword"; let override = "another keyword" // statements can be separated by a semi-colon @@ -39,7 +41,7 @@ optionalString = nil /* Comment here /* - Nested comment here + Nested comments are also supported */ */ @@ -119,7 +121,7 @@ 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 with Swift function docs +// Function with Swift header docs (format as reStructedText) /** A greet operation @@ -188,12 +190,34 @@ numbers = sorted(numbers, < ) print(numbers) // [3, 6, 18] +// +// MARK: Structures +// + +// Structures and classes have very similar capabilites +struct NamesTable { + let names: [String] + + // Custom subscript + subscript(index: Int) -> String { + return names[index] + } +} + +// Structures have an auto-generated (implicit) designated initializer +let namesTable = NamesTable(names: ["Me", "Them"]) +//let name = namesTable[2] +//println("Name is \(name)") // Name is Them + // // MARK: Classes // -class Shape { - func getArea() -> Int { +// Classes, structures and its members have three levels of access control +// They are: internal (default), public, private + +public class Shape { + public func getArea() -> Int { return 0; } } @@ -203,23 +227,29 @@ class Shape { // structured object, you should use a `struct` // A simple class `Square` extends `Shape` -class Rect: Shape { +internal class Rect: Shape { var sideLength: Int = 1 // Custom getter and setter property - var perimeter: Int { + private var perimeter: Int { get { return 4 * sideLength } set { + // `newValue` is an implicit variable available to setters sideLength = newValue / 4 } } + + // Lazily load a property + // subShape remains nil (uninitialized) until getter called + lazy var subShape = Rect(sideLength: 4) // If you don't need a custom getter and setter, // but still want to run code before and after getting or setting // a property, you can use `willSet` and `didSet` var identifier: String = "defaultID" { + // the `willSet` arg will be the variable name for the new value willSet(someIdentifier) { print(someIdentifier) } @@ -254,7 +284,7 @@ print(mySquare.sideLength) // 4 // compare instances, not the same as == which compares objects (equal to) if mySquare === mySquare { - println("Yep its mySquare") + println("Yep, it's mySquare") } @@ -279,15 +309,47 @@ enum Suit { // -// MARK: Other +// MARK: Protocols // -// `protocol`: Similar to Java interfaces. +// `protocol`s can require that conforming types have specific +// instance properties, instance methods, type methods, +// operators, and subscripts. + protocol ShapeGenerator { + var enabled: Bool { get set } func buildShape() -> Shape } +/* +// Protocols declared with @objc allow optional functions, +// which allow you to check for conformance +@objc protocol TransformShape { + optional func reshaped() + optional func canReshape() -> Bool +} + +class MyShape: Rect { + var delegate: TransformShape? + + func grow() { + sideLength += 2 + + if let allow = self.delegate?.canReshape?() { + // test for delegate then for method + self.delegate?.reshaped?() + } + } +} +*/ + +// +// MARK: Other +// + // `extension`s: Add extra functionality to an already existing type + +// Square now "conforms" to the `Printable` protocol extension Square: Printable { var description: String { return "Area: \(self.getArea()) - ID: \(self.identifier)" @@ -321,7 +383,8 @@ func findIndex(array: [T], valueToFind: T) -> Int? { } return nil } - +let foundAtIndex = findIndex([1, 2, 3, 4], 3) +println(foundAtIndex == 2) // true // Operators: // Custom operators can start with the characters: @@ -330,13 +393,17 @@ func findIndex(array: [T], valueToFind: T) -> Int? { // Unicode math, symbol, arrow, dingbat, and line/box drawing characters. prefix operator !!! {} -// An operator that triples the side length when used +// A prefix 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) +// current value +println(mySquare.sideLength) // 4 + +// change side length using custom !!! operator, increases size by 3 +!!!mySquare +println(mySquare.sideLength) // 12 ``` -- cgit v1.2.3 From eab554a7a7f2869ff7dac9f54acce9a7ed55cfa4 Mon Sep 17 00:00:00 2001 From: Adam Date: Mon, 8 Sep 2014 13:08:28 +0200 Subject: Review docs for added rouge lexers and update those with new highlighters --- swift.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'swift.html.markdown') diff --git a/swift.html.markdown b/swift.html.markdown index e7f2f9a2..77047355 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -12,7 +12,7 @@ The official [Swift Programming Language](https://itunes.apple.com/us/book/swift See also Apple's [getting started guide](https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/LandingPage/index.html), which has a complete tutorial on Swift. -```js +```swift // // MARK: Basics // -- cgit v1.2.3