mirror of
https://github.com/adambard/learnxinyminutes-docs.git
synced 2024-12-23 15:24:09 +03:00
Updated code according Swift v.3 (#2427)
* Updated code according Swift v.3 * [swift] Removed "where" in conditional statements
This commit is contained in:
parent
8425960f4b
commit
b738126423
@ -7,6 +7,7 @@ contributors:
|
|||||||
- ["Anthony Nguyen", "http://github.com/anthonyn60"]
|
- ["Anthony Nguyen", "http://github.com/anthonyn60"]
|
||||||
- ["Clayton Walker", "https://github.com/cwalk"]
|
- ["Clayton Walker", "https://github.com/cwalk"]
|
||||||
- ["Fernando Valverde", "http://visualcosita.xyz"]
|
- ["Fernando Valverde", "http://visualcosita.xyz"]
|
||||||
|
- ["Alexey Nazaroff", "https://github.com/rogaven"]
|
||||||
filename: learnswift.swift
|
filename: learnswift.swift
|
||||||
---
|
---
|
||||||
|
|
||||||
@ -104,10 +105,12 @@ if let someOptionalStringConstant = someOptionalString {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Swift has support for storing a value of any type.
|
// Swift has support for storing a value of any type.
|
||||||
// AnyObject == id
|
// For that purposes there is two keywords: `Any` and `AnyObject`
|
||||||
// Unlike Objective-C `id`, AnyObject works with any value (Class, Int, struct, etc.)
|
// `AnyObject` == `id` from Objective-C
|
||||||
var anyObjectVar: AnyObject = 7
|
// `Any` – also works with any scalar values (Class, Int, struct, etc.)
|
||||||
anyObjectVar = "Changed value to a string, not good practice, but possible."
|
var anyVar: Any = 7
|
||||||
|
anyVar = "Changed value to a string, not good practice, but possible."
|
||||||
|
let anyObjectVar: AnyObject = Int(1) as NSNumber
|
||||||
|
|
||||||
/*
|
/*
|
||||||
Comment here
|
Comment here
|
||||||
@ -151,11 +154,11 @@ var explicitEmptyMutableDictionary: [String: Float] = [:] // same as above
|
|||||||
// MARK: Control Flow
|
// MARK: Control Flow
|
||||||
//
|
//
|
||||||
|
|
||||||
// Condition statements support "where" clauses, which can be used
|
// Condition statements support "," (comma) clauses, which can be used
|
||||||
// to help provide conditions on optional values.
|
// to help provide conditions on optional values.
|
||||||
// Both the assignment and the "where" clause must pass.
|
// Both the assignment and the "," clause must pass.
|
||||||
let someNumber = Optional<Int>(7)
|
let someNumber = Optional<Int>(7)
|
||||||
if let num = someNumber where num > 3 {
|
if let num = someNumber, num > 3 {
|
||||||
print("num is greater than 3")
|
print("num is greater than 3")
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -230,13 +233,13 @@ A greet operation
|
|||||||
func greet(name: String, day: String) -> String {
|
func greet(name: String, day: String) -> String {
|
||||||
return "Hello \(name), today is \(day)."
|
return "Hello \(name), today is \(day)."
|
||||||
}
|
}
|
||||||
greet("Bob", day: "Tuesday")
|
greet(name: "Bob", day: "Tuesday")
|
||||||
|
|
||||||
// similar to above except for the function parameter behaviors
|
// similar to above except for the function parameter behaviors
|
||||||
func greet2(requiredName requiredName: String, externalParamName localParamName: String) -> String {
|
func greet2(name: String, externalParamName localParamName: String) -> String {
|
||||||
return "Hello \(requiredName), the day is \(localParamName)"
|
return "Hello \(name), the day is \(localParamName)"
|
||||||
}
|
}
|
||||||
greet2(requiredName: "John", externalParamName: "Sunday")
|
greet2(name: "John", externalParamName: "Sunday")
|
||||||
|
|
||||||
// Function that returns multiple items in a tuple
|
// Function that returns multiple items in a tuple
|
||||||
func getGasPrices() -> (Double, Double, Double) {
|
func getGasPrices() -> (Double, Double, Double) {
|
||||||
@ -279,7 +282,7 @@ func setup(numbers: Int...) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Passing and returning functions
|
// Passing and returning functions
|
||||||
func makeIncrementer() -> (Int -> Int) {
|
func makeIncrementer() -> ((Int) -> Int) {
|
||||||
func addOne(number: Int) -> Int {
|
func addOne(number: Int) -> Int {
|
||||||
return 1 + number
|
return 1 + number
|
||||||
}
|
}
|
||||||
@ -289,14 +292,14 @@ var increment = makeIncrementer()
|
|||||||
increment(7)
|
increment(7)
|
||||||
|
|
||||||
// pass by ref
|
// pass by ref
|
||||||
func swapTwoInts(inout a: Int, inout b: Int) {
|
func swapTwoInts(a: inout Int, b: inout Int) {
|
||||||
let tempA = a
|
let tempA = a
|
||||||
a = b
|
a = b
|
||||||
b = tempA
|
b = tempA
|
||||||
}
|
}
|
||||||
var someIntA = 7
|
var someIntA = 7
|
||||||
var someIntB = 3
|
var someIntB = 3
|
||||||
swapTwoInts(&someIntA, b: &someIntB)
|
swapTwoInts(a: &someIntA, b: &someIntB)
|
||||||
print(someIntB) // 7
|
print(someIntB) // 7
|
||||||
|
|
||||||
|
|
||||||
@ -324,7 +327,7 @@ numbers = numbers.map({ number in 3 * number })
|
|||||||
print(numbers) // [3, 6, 18]
|
print(numbers) // [3, 6, 18]
|
||||||
|
|
||||||
// Trailing closure
|
// Trailing closure
|
||||||
numbers = numbers.sort { $0 > $1 }
|
numbers = numbers.sorted { $0 > $1 }
|
||||||
|
|
||||||
print(numbers) // [18, 6, 3]
|
print(numbers) // [18, 6, 3]
|
||||||
|
|
||||||
@ -351,8 +354,8 @@ print("Name is \(name)") // Name is Them
|
|||||||
// MARK: Error Handling
|
// MARK: Error Handling
|
||||||
//
|
//
|
||||||
|
|
||||||
// The `ErrorType` protocol is used when throwing errors to catch
|
// The `Error` protocol is used when throwing errors to catch
|
||||||
enum MyError: ErrorType {
|
enum MyError: Error {
|
||||||
case BadValue(msg: String)
|
case BadValue(msg: String)
|
||||||
case ReallyBadValue(msg: String)
|
case ReallyBadValue(msg: String)
|
||||||
}
|
}
|
||||||
@ -368,15 +371,15 @@ func fakeFetch(value: Int) throws -> String {
|
|||||||
|
|
||||||
func testTryStuff() {
|
func testTryStuff() {
|
||||||
// assumes there will be no error thrown, otherwise a runtime exception is raised
|
// assumes there will be no error thrown, otherwise a runtime exception is raised
|
||||||
let _ = try! fakeFetch(7)
|
let _ = try! fakeFetch(value: 7)
|
||||||
|
|
||||||
// if an error is thrown, then it proceeds, but if the value is nil
|
// if an error is thrown, then it proceeds, but if the value is nil
|
||||||
// it also wraps every return value in an optional, even if its already optional
|
// it also wraps every return value in an optional, even if its already optional
|
||||||
let _ = try? fakeFetch(7)
|
let _ = try? fakeFetch(value: 7)
|
||||||
|
|
||||||
do {
|
do {
|
||||||
// normal try operation that provides error handling via `catch` block
|
// normal try operation that provides error handling via `catch` block
|
||||||
try fakeFetch(1)
|
try fakeFetch(value: 1)
|
||||||
} catch MyError.BadValue(let msg) {
|
} catch MyError.BadValue(let msg) {
|
||||||
print("Error message: \(msg)")
|
print("Error message: \(msg)")
|
||||||
} catch {
|
} catch {
|
||||||
@ -570,10 +573,11 @@ protocol ShapeGenerator {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Protocols declared with @objc allow optional functions,
|
// Protocols declared with @objc allow optional functions,
|
||||||
// which allow you to check for conformance
|
// which allow you to check for conformance. These functions must be
|
||||||
|
// marked with @objc also.
|
||||||
@objc protocol TransformShape {
|
@objc protocol TransformShape {
|
||||||
optional func reshape()
|
@objc optional func reshape()
|
||||||
optional func canReshape() -> Bool
|
@objc optional func canReshape() -> Bool
|
||||||
}
|
}
|
||||||
|
|
||||||
class MyShape: Rect {
|
class MyShape: Rect {
|
||||||
@ -585,7 +589,7 @@ class MyShape: Rect {
|
|||||||
// Place a question mark after an optional property, method, or
|
// Place a question mark after an optional property, method, or
|
||||||
// subscript to gracefully ignore a nil value and return nil
|
// subscript to gracefully ignore a nil value and return nil
|
||||||
// instead of throwing a runtime error ("optional chaining").
|
// instead of throwing a runtime error ("optional chaining").
|
||||||
if let reshape = self.delegate?.canReshape?() where reshape {
|
if let reshape = self.delegate?.canReshape?(), reshape {
|
||||||
// test for delegate then for method
|
// test for delegate then for method
|
||||||
self.delegate?.reshape?()
|
self.delegate?.reshape?()
|
||||||
}
|
}
|
||||||
@ -620,20 +624,20 @@ extension Int {
|
|||||||
}
|
}
|
||||||
|
|
||||||
print(7.customProperty) // "This is 7"
|
print(7.customProperty) // "This is 7"
|
||||||
print(14.multiplyBy(3)) // 42
|
print(14.multiplyBy(num: 3)) // 42
|
||||||
|
|
||||||
// Generics: Similar to Java and C#. Use the `where` keyword to specify the
|
// Generics: Similar to Java and C#. Use the `where` keyword to specify the
|
||||||
// requirements of the generics.
|
// requirements of the generics.
|
||||||
|
|
||||||
func findIndex<T: Equatable>(array: [T], _ valueToFind: T) -> Int? {
|
func findIndex<T: Equatable>(array: [T], valueToFind: T) -> Int? {
|
||||||
for (index, value) in array.enumerate() {
|
for (index, value) in array.enumerated() {
|
||||||
if value == valueToFind {
|
if value == valueToFind {
|
||||||
return index
|
return index
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
let foundAtIndex = findIndex([1, 2, 3, 4], 3)
|
let foundAtIndex = findIndex(array: [1, 2, 3, 4], valueToFind: 3)
|
||||||
print(foundAtIndex == 2) // true
|
print(foundAtIndex == 2) // true
|
||||||
|
|
||||||
// Operators:
|
// Operators:
|
||||||
@ -641,10 +645,10 @@ print(foundAtIndex == 2) // true
|
|||||||
// / = - + * % < > ! & | ^ . ~
|
// / = - + * % < > ! & | ^ . ~
|
||||||
// or
|
// or
|
||||||
// Unicode math, symbol, arrow, dingbat, and line/box drawing characters.
|
// Unicode math, symbol, arrow, dingbat, and line/box drawing characters.
|
||||||
prefix operator !!! {}
|
prefix operator !!!
|
||||||
|
|
||||||
// A prefix operator that triples the side length when used
|
// A prefix operator that triples the side length when used
|
||||||
prefix func !!! (inout shape: Square) -> Square {
|
prefix func !!! (shape: inout Square) -> Square {
|
||||||
shape.sideLength *= 3
|
shape.sideLength *= 3
|
||||||
return shape
|
return shape
|
||||||
}
|
}
|
||||||
@ -657,8 +661,8 @@ print(mySquare.sideLength) // 4
|
|||||||
print(mySquare.sideLength) // 12
|
print(mySquare.sideLength) // 12
|
||||||
|
|
||||||
// Operators can also be generics
|
// Operators can also be generics
|
||||||
infix operator <-> {}
|
infix operator <->
|
||||||
func <-><T: Equatable> (inout a: T, inout b: T) {
|
func <-><T: Equatable> (a: inout T, b: inout T) {
|
||||||
let c = a
|
let c = a
|
||||||
a = b
|
a = b
|
||||||
b = c
|
b = c
|
||||||
|
Loading…
Reference in New Issue
Block a user