Google C++编程风格指南

Standard
July 14, 2013
作者:Hawstein
出处:http://hawstein.com/posts/google-cpp-style-guide.html
声明:本文采用以下协议进行授权: 自由转载-非商用-非衍生-保持署名|Creative Commons BY-NC-ND 3.0 ,转载请注明作者及出处。

前言

越来越发现一致的编程风格的重要性,于是把Google的C++编程风格指南看了一遍, 这里记录下于自己有益的rules。当规则有多个选择时,这里只记录个人习惯的用法, 并不代表它是唯一的用法。

Google Style Guide

Google开源项目风格指南

命名约定

命名管理是最重要的一致性规则,因此我把它放在最前面。

  • 尽可能给出描述性名称。
int num_errors; 
int num_completed_connections;
  • 文件名全部小写,用下划线做连接符。
my_useful_class.cc
  • C++文件以.cc 结尾,头文件以.h 结尾。(从.cpp切换到.cc)
my_useful_class.cc
my_useful_class.h
  • 类型命名每个单词以大写字母开头,不包含下划线。类、结构体、类型定义(typedef) 、枚举都使用相同约定。
// classes and structs
class UrlTable { ...
class UrlTableTester { ...
struct UrlTableProperties { ...

// typedefs
typedef hash_map<UrlTableProperties *, string> PropertiesMap;

// enums
enum UrlTableErrors { ...
  • 变量名一律小写,单词之间用下划线连接。类的成员变量以下划线结尾。
my_exciting_local_variable
my_exciting_member_variable_
  • 结构体的数据成员可以和普通变量一样,不用像类那样接下划线。
struct UrlTableProperties {
    string name;
    int num_entries;
}
  • 少用全局变量,要用的话用g作为其前缀(不喜欢用g_)。
bool gInvalid = false;
  • 常量命名在名称前加k。
const int kDaysInAWeek = 7;
  • 函数名的每个单词首字母大写,没有下划线。
AddTableEntry()
DeleteUrl()
  • 取值和设值函数要与存取的变量名匹配,使用小写单词及下划线。
class MyClass {
public:
    ...
    int num_entries() const { return num_entries_; }
    void set_num_entries(int num_entries) { num_entries_ = num_entries; }

private:
    int num_entries_;
};
  • 非常短小的内联函数也可以用小写字母命名。
void swap(int &a, int &b);
int max(int a, int b);
bool cmp(Type t1, Type t2);
  • 名字空间用小写字母命名,并基于项目名称和目录结构:
namespace google_awesome_project {
    ...
}
  • 枚举值应该优先采用常量的命名方式。
enum UrlTableErrors {
    kOK = 0,
    kErrorOutOfMemory,
    kErrorMalformedInput,
};
  • 尽量避免使用宏,如果不得不用,请使用大写字母及下划线。
#define ROUND(x) ...
#define PI_ROUNDED 3.0

把《The Swift Programming Language》读薄

Standard
July 1, 2014
作者:Hawstein
出处:http://hawstein.com/posts/make-thiner-tspl.html
声明:本文采用以下协议进行授权: 自由转载-非商用-非衍生-保持署名|Creative Commons BY-NC-ND 3.0 ,转载请注明作者及出处。

目录

  1. About Swift
  2. The Basics
  3. Basic Operators
  4. Strings and Characters
  5. Collection Types
  6. Control Flow
  7. Functions
  8. Closures
  9. Enumerations
  10. Classes and Structures
  11. Properties
  12. Methods
  13. Subscripts
  14. Inheritance
  15. Initialization
  16. Deinitialization
  17. Automatic Reference Counting
  18. Optional Chaining
  19. Type Casting
  20. Nested Types
  21. Extensions
  22. Protocols
  23. Generics
  24. Advanced Operators
  25. A Swift Tour // 放到最后避免有人看不懂

About Swift

We simplified memory management with Automatic Reference Counting.

Swift provides seamless access to existing Cocoa frameworks and mix-and-match interoperability with Objective-C code.

The Basics

let声明常量,var声明变量

You can access the minimum and maximum values of each integer type with its min and max properties.

虽然有UInt,但能用Int的时候就用Int。

// 各种进制的字面量表示
let decimalInteger = 17
let binaryInteger = 0b10001       // 17 in binary notation
let octalInteger = 0o21           // 17 in octal notation
let hexadecimalInteger = 0x11     // 17 in hexadecimal notation

// 更易于阅读的写法
let paddedDouble = 000123.456
let oneMillion = 1_000_000
let justOverOneMillion = 1_000_000.000_000_1

Floating-point values are always truncated when used to initialize a new integer value in this way. This means that 4.75 becomes 4, and -3.9 becomes -3.

// 定义类型别名 typealias
typealias AudioSample = UInt16 

// optional binding,只有当yyy是optional的时候才可以这样用。optional的yyy非空时为真,将yyy中的值取出赋给xxx,空时(nil)为假;

if let xxx = yyy {
     // do something
} else {
     // do other thing
}

// decompose一个tuple时,对于不想使用的元素用’_’接收
let http404Error = (404, "Not Found")
let (justTheStatusCode, _) = http404Error
println("The status code is \(justTheStatusCode)")
// prints "The status code is 404

let possibleNumber = "123"
let convertedNumber = possibleNumber.toInt()
// convertedNumber is inferred to be of type "Int?", or "optional Int”,因为toInt()可能会失败(比如“123a”)导致返回nil

You can use an if statement to find out whether an optional contains a value. If an optional does have a value, it evaluates to true; if it has no value at all, it evaluates to false.

Once you’re sure that the optional does contain a value, you can access its underlying value by adding an exclamation mark (!) to the end of the optional’s name. The exclamation mark effectively says, “I know that this optional definitely has a value; please use it.” This is known as forced unwrapping of the optional’s value。

If you define an optional constant or variable without providing a default value, the constant or variable is automatically set to nil for you.

Basic Operators

Unlike C, Swift lets you perform remainder (%) calculations on floating-point numbers.

if x = y {
    // this is not valid, because x = y does not return a value
}

// Swift中的取模操作
-9 % 4   // equals -1,理解成:-9 = (4 × -2) + -1

Swift also provides two identity operators (=== and !==), which you use to test whether two object references both refer to the same object instance

// ???
var arr1 = [1, 2, 3]
var arr2 = arr1
arr2[0] = 10;
arr1     // [10, 2, 3]
arr2     // [10, 2, 3]
arr1 === arr2  // 修改arr2,arr1也跟着修改,所以应该是指向一个object,这里应该是true,但结果却是false

String and Characters

Swift’s String type is a value type. If you create a new String value, that String value is copied when it is passed to a function or method, or when it is assigned to a constant or variable.

String判断是否包含某前缀或后缀的方法:hasPrefix,hasSuffix

String怎么随机取其中一个字符?

Collection Types

// arr随着brr改变
var arr = ["hello", "world"]
var brr = arr
brr[0] = "haw"
brr     // ["haw", "world"]
arr     // ["haw", "world"]


// arr不随brr改变,说明brr原本与arr指向一块内存,以下操作后指向新的内存,并把数组中的元素值copy了一遍。
// 长度发生变化时,Array会发生拷贝
var arr = ["hello", "world"]
var brr = arr
brr[0..0] = ["haw"]
brr     // ["haw", "hello", "world”]
arr      //  ["hello", "world"]


// arr不随brr改变,同上
var arr = ["hello", "world"]
var brr = arr
brr.insert("haw", atIndex: 0)      // remove也一样

brr     // ["haw", "hello", "world”]
arr      //  ["hello", "world"]
for (index, value) in enumerate(shoppingList) {
    println("Item \(index + 1): \(value)")
}
// Item 1: Six eggs
// Item 2: Milk
// Item 3: Flour
// Item 4: Baking Powder
// Item 5: Bananas
var threeDoubles = Double[](count: 3, repeatedValue: 0.0)
// threeDoubles is of type Double[], and equals [0.0, 0.0, 0.0]
var anotherThreeDoubles = Array(count: 3, repeatedValue: 2.5)
// anotherThreeDoubles is inferred as Double[], and equals [2.5, 2.5, 2.5]

The only restriction is that KeyType must be hashable—that is, it must provide a way to make itself uniquely representable. All of Swift’s basic types (such as String, Int, Double, and Bool) are hashable by default, and all of these types can be used as the keys of a dictionary. Enumeration member values without associated values (as described in Enumerations) are also hashable by default.

// 以下将字典airports中key为DUB的值更新为Dublin International,返回的是它原来的值
if let oldValue = airports.updateValue("Dublin International", forKey: "DUB") {
    println("The old value for DUB was \(oldValue).")
}
// prints "The old value for DUB was Dublin.

You can also use subscript syntax to retrieve a value from the dictionary for a particular key. Because it is possible to request a key for which no value exists, a dictionary’s subscript returns an optional value of the dictionary’s value type.

airports["APL"] = "Apple International"
// "Apple International" is not the real airport for APL, so delete it
airports["APL"] = nil
// APL has now been removed from the dictionary

if let removedValue = airports.removeValueForKey("DUB") {
    println("The removed airport's name is \(removedValue).")
} else {
    println("The airports dictionary does not contain a value for DUB.")
}
// prints "The removed airport's name is Dublin International.

//
for airportCode in airports.keys {
    println("Airport code: \(airportCode)")
}
// Airport code: TYO
// Airport code: LHR

for airportName in airports.values {
    println("Airport name: \(airportName)")
}
// Airport name: Tokyo
// Airport name: London Heathrow

let airportCodes = Array(airports.keys)
// airportCodes is ["TYO", "LHR"]

let airportNames = Array(airports.values)
// airportNames is ["Tokyo", "London Heathrow"]

Arrays and dictionaries store multiple values together in a single collection. If you create an array or a dictionary and assign it to a variable, the collection that is created will be mutable. This means that you can change (or mutate) the size of the collection after it is created by adding more items to the collection, or by removing existing items from the ones it already contains. Conversely, if you assign an array or a dictionary to a constant, that array or dictionary is immutable, and its size cannot be changed.

For dictionaries, immutability also means that you cannot replace the value for an existing key in the dictionary. An immutable dictionary’s contents cannot be changed once they are set.

Immutability has a slightly different meaning for arrays, however. You are still not allowed to perform any action that has the potential to change the size of an immutable array, but you are allowed to set a new value for an existing index in the array. This enables Swift’s Array type to provide optimal performance for array operations when the size of an array is fixed.

Control Flow

let base = 3
let power = 10
var answer = 1
for _ in 1...power {
    answer *= base
}
println("\(base) to the power of \(power) is \(answer)")
// prints "3 to the power of 10 is 59049

switch中的case情况要穷尽所有的可能性,如果可以穷尽(比如case是enum类型的有限几个值)则可以不加default,否则一定要加default。case中可以使用区间,开闭都可以。

let count = 3_000_000_000_000
let countedThings = "stars in the Milky Way"
var naturalCount: String
switch count {
case 0:
    naturalCount = "no"
case 1...3:
    naturalCount = "a few"
case 4...9:
    naturalCount = "several"
case 10...99:
    naturalCount = "tens of"
case 100...999:
    naturalCount = "hundreds of"
case 1000...999_999:
    naturalCount = "thousands of"
default:
    naturalCount = "millions and millions of"
}
println("There are \(naturalCount) \(countedThings).")
// prints "There are millions and millions of stars in the Milky Way.


let somePoint = (1, 1)
switch somePoint {
case (0, 0):
    println("(0, 0) is at the origin")
case (_, 0):
    println("(\(somePoint.0), 0) is on the x-axis")
case (0, _):
    println("(0, \(somePoint.1)) is on the y-axis")
case (-2...2, -2...2):
    println("(\(somePoint.0), \(somePoint.1)) is inside the box")
default:
    println("(\(somePoint.0), \(somePoint.1)) is outside of the box")
}
// prints "(1, 1) is inside the box

Unlike C, Swift allows multiple switch cases to consider the same value or values. In fact, the point (0, 0) could match all four of the cases in this example. However, if multiple matches are possible, the first matching case is always used. The point (0, 0) would match case (0, 0) first, and so all other matching cases would be ignored.

switch anotherPoint {
case (let x, 0):
    println("on the x-axis with an x value of \(x)")
case (0, let y):
    println("on the y-axis with a y value of \(y)")
case let (x, y):
    println("somewhere else at (\(x), \(y))")
}
// prints "on the x-axis with an x value


let yetAnotherPoint = (1, -1)
switch yetAnotherPoint {
case let (x, y) where x == y:
    println("(\(x), \(y)) is on the line x == y")
case let (x, y) where x == -y:
    println("(\(x), \(y)) is on the line x == -y")
case let (x, y):
    println("(\(x), \(y)) is just some arbitrary point")
}
// prints "(1, -1) is on the line x == -y 

let integerToDescribe = 5
var description = "The number \(integerToDescribe) is"
switch integerToDescribe {
case 2, 3, 5, 7, 11, 13, 17, 19:
    description += " a prime number, and also"
    fallthrough
default:
    description += " an integer."
}
println(description)
// prints "The number 5 is a prime number, and also an integer.


gameLoop: while square != finalSquare {
    if ++diceRoll == 7 { diceRoll = 1 }
    switch square + diceRoll {
    case finalSquare:
        // diceRoll will move us to the final square, so the game is over
        break gameLoop
    case let newSquare where newSquare > finalSquare:
        // diceRoll will move us beyond the final square, so roll again
        continue gameLoop
    default:
        // this is a valid move, so find out its effect
        square += diceRoll
        square += board[square]
    }
}
println("Game over!")

Functions

If you provide an external parameter name for a parameter, that external name must always be used when calling the function.

func join(string s1: String, toString s2: String, withJoiner joiner: String)
    -> String {
        return s1 + joiner + s2
}
join(string: "hello", toString: "world", withJoiner: ", ")
// returns "hello, world"  
func containsCharacter(#string: String, #characterToFind: Character) -> Bool {
    for character in string {
        if character == characterToFind {
            return true
        }
    }
    return false
}

let containsAVee = containsCharacter(string: "aardvark", characterToFind: "v")
// containsAVee equals true, because "aardvark" contains a "v"
func join(string s1: String, toString s2: String,
    withJoiner joiner: String = " ") -> String {
        return s1 + joiner + s2
}
join(string: "hello", toString: "world", withJoiner: "-")
// returns "hello-world”
join(string: "hello", toString: "world")
// returns "hello world"   
func join(s1: String, s2: String, joiner: String = " ") -> String {
    return s1 + joiner + s2
}
join("hello", "world", joiner: "-")
// returns "hello-world”  有默认值的参数,如果你没有使用外部参数名,Swift会自动提供一个和内部参数名一样的外部参数名
func arithmeticMean(numbers: Double...) -> Double {
    var total: Double = 0
    for number in numbers {
        total += number
    }
    return total / Double(numbers.count)
}
arithmeticMean(1, 2, 3, 4, 5)
// returns 3.0, which is the arithmetic mean of these five numbers
arithmeticMean(3, 8, 19)
// returns 10.0, which is the arithmetic mean of these three numbers 

A function may have at most one variadic parameter, and it must always appear last in the parameter list, to avoid ambiguity when calling the function with multiple parameters.

If your function has one or more parameters with a default value, and also has a variadic parameter, place the variadic parameter after all the defaulted parameters at the very end of the list.

形参默认是常量,如果要改变形参,需要用var显式声明为变量 // swift中有许多默认情况和主流(比如C\C++)语言都是相反的,它将更常见的情况设定为默认

func alignRight(var string: String, count: Int, pad: Character) -> String {
    let amountToPad = count - countElements(string)
    for _ in 1...amountToPad {
        string = pad + string
    }
    return string
}
let originalString = "hello"
let paddedString = alignRight(originalString, 10, "-")
// paddedString is equal to "-----hello"
// originalString is still equal to "hello" 

In-out parameters cannot have default values, and variadic parameters cannot be marked as inout. If you mark a parameter as inout, it cannot also be marked as var or let.

func swapTwoInts(inout a: Int, inout b: Int) { // 类似于引用传参
    let temporaryA = a
    a = b
    b = temporaryA
} 

var someInt = 3
var anotherInt = 107
swapTwoInts(&someInt, &anotherInt)
println("someInt is now \(someInt), and anotherInt is now \(anotherInt)")
// prints "someInt is now 107, and anotherInt is now 3" 

像定义常量或变量一样定义函数:

var mathFunction: (Int, Int) -> Int = addTwoInts
println("Result: \(mathFunction(2, 3))")
// prints "Result: 5”

let anotherMathFunction = addTwoInts
// anotherMathFunction is inferred to be of type (Int, Int) -> Int   
func printMathResult(mathFunction: (Int, Int) -> Int, a: Int, b: Int) {
    println("Result: \(mathFunction(a, b))")
}
printMathResult(addTwoInts, 3, 5)
// prints "Result: 8" 

Swift支持嵌套函数:

func chooseStepFunction(backwards: Bool) -> (Int) -> Int {
    func stepForward(input: Int) -> Int { return input + 1 }
    func stepBackward(input: Int) -> Int { return input - 1 }
    return backwards ? stepBackward : stepForward
}
var currentValue = -4
let moveNearerToZero = chooseStepFunction(currentValue > 0)
// moveNearerToZero now refers to the nested stepForward() function
while currentValue != 0 {
    println("\(currentValue)... ")
    currentValue = moveNearerToZero(currentValue)
}
println("zero!")
// -4...
// -3...
// -2...
// -1...
// zero! 

Closures

Global and nested functions, as introduced in Functions, are actually special cases of closures. Closures take one of three forms:

  • Global functions are closures that have a name and do not capture any values.
  • Nested functions are closures that have a name and can capture values from their enclosing function.
  • Closure expressions are unnamed closures written in a lightweight syntax that can capture values from their surrounding context.

Closure expression syntax has the following general form:

{ (parameters) -> return type in
    statements
}
let names = ["Chris", "Alex", "Ewa", "Barry", "Daniella”]
func backwards(s1: String, s2: String) -> Bool {
    return s1 > s2
}
// 方法1
var reversed = sort(names, backwards)
// reversed is equal to ["Ewa", "Daniella", "Chris", "Barry", "Alex”]  

// 1.5
reversed = sort(names, { (s1: String, s2: String) -> Bool in return s1 > s2 } )

// 方法2
reversed = sort(names, { s1, s2 in return s1 > s2 } ) 

// 方法3
reversed = sort(names, { s1, s2 in s1 > s2 } ) // Implicit Returns from Single-Expression Closures

// 方法4
reversed = sort(names, { $0 > $1 } )  

// 方法5
reversed = sort(names, >) 

// 方法6
reversed = sort(names) { $0 > $1 } 

It is always possible to infer parameter types and return type when passing a closure to a function as an inline closure expression. As a result, you rarely need to write an inline closure in its fullest form.

func someFunctionThatTakesAClosure(closure: () -> ()) {
    // function body goes here
}

// here's how you call this function without using a trailing closure:

someFunctionThatTakesAClosure({
    // closure's body goes here
    })

// here's how you call this function with a trailing closure instead:

someFunctionThatTakesAClosure() {
    // trailing closure's body goes here
} 

If a closure expression is provided as the function’s only argument and you provide that expression as a trailing closure, you do not need to write a pair of parentheses () after the function’s name when you call the function.

let digitNames = [
    0: "Zero", 1: "One", 2: "Two",   3: "Three", 4: "Four",
    5: "Five", 6: "Six", 7: "Seven", 8: "Eight", 9: "Nine"
]
let numbers = [16, 58, 510] 
let strings = numbers.map {
    (var number) -> String in
    var output = ""
    while number > 0 {
        output = digitNames[number % 10]! + output
        number /= 10
    }
    return output
}
// strings is inferred to be of type String[]
// its value is ["OneSix", "FiveEight", "FiveOneZero"] 
func makeIncrementor(forIncrement amount: Int) -> () -> Int {
    var runningTotal = 0
    func incrementor() -> Int {
        runningTotal += amount
        return runningTotal
    }
    return incrementor
}

let incrementByTen = makeIncrementor(forIncrement: 10)
incrementByTen()
// returns a value of 10
incrementByTen()
// returns a value of 20
incrementByTen()
// returns a value of 30

let incrementBySeven = makeIncrementor(forIncrement: 7)
incrementBySeven()
// returns a value of 7
incrementByTen()
// returns a value of 40    

let alsoIncrementByTen = incrementByTen
alsoIncrementByTen()
// returns a value of 50 

functions and closures are reference types.

Enumerations

enum CompassPoint {
    case North
    case South
    case East
    case West
} 

enum Planet {
    case Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune
}

var directionToHead = CompassPoint.West
directionToHead = .East   

directionToHead = .South
switch directionToHead {
case .North:
    println("Lots of planets have a north")
case .South:
    println("Watch out for penguins")
case .East:
    println("Where the sun rises")
case .West:
    println("Where the skies are blue")
}
// prints "Watch out for penguins" 
let somePlanet = Planet.Earth
switch somePlanet {
case .Earth:
    println("Mostly harmless")
default:
    println("Not a safe place for humans")
}
// prints "Mostly harmless" 
enum Barcode {
    case UPCA(Int, Int, Int)
    case QRCode(String)
}

var productBarcode = Barcode.UPCA(8, 85909_51226, 3)
productBarcode = .QRCode("ABCDEFGHIJKLMNOP”)

switch productBarcode {
case .UPCA(let numberSystem, let identifier, let check):
    println("UPC-A with value of \(numberSystem), \(identifier), \(check).")
case .QRCode(let productCode):
    println("QR code with value of \(productCode).")
}
// prints "QR code with value of ABCDEFGHIJKLMNOP.”    

switch productBarcode {
case let .UPCA(numberSystem, identifier, check):
    println("UPC-A with value of \(numberSystem), \(identifier), \(check).")
case let .QRCode(productCode):
    println("QR code with value of \(productCode).")
}
// prints "QR code with value of ABCDEFGHIJKLMNOP." 
// raw values
enum ASCIIControlCharacter: Character {
    case Tab = "\t"
    case LineFeed = "\n"
    case CarriageReturn = "\r"
} 

enum Planet: Int {
    case Mercury = 1, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune
} 

let earthsOrder = Planet.Earth.toRaw()
// earthsOrder is 3

let possiblePlanet = Planet.fromRaw(7)
// possiblePlanet is of type Planet? and equals Planet.Uranus

let positionToFind = 9
if let somePlanet = Planet.fromRaw(positionToFind) {
    switch somePlanet {
    case .Earth:
        println("Mostly harmless")
    default:
        println("Not a safe place for humans")
    }
} else {
    println("There isn't a planet at position \(positionToFind)")
}
// prints "There isn't a planet at position 9"   

Classes and Structures

Classes have additional capabilities that structures do not:

Inheritance enables one class to inherit the characteristics of another. Type casting enables you to check and interpret the type of a class instance at runtime. Deinitializers enable an instance of a class to free up any resources it has assigned. Reference counting allows more than one reference to a class instance.

Structures are always copied when they are passed around in your code, and do not use reference counting.

if tenEighty === alsoTenEighty {
    println("tenEighty and alsoTenEighty refer to the same Resolution instance.")
}
// prints "tenEighty and alsoTenEighty refer to the same Resolution instance.”

Whenever you assign a Dictionary instance to a constant or variable, or pass a Dictionary instance as an argument to a function or method call, the dictionary is copied at the point that the assignment or call takes place.

var ages = ["Peter": 23, "Wei": 35, "Anish": 65, "Katya": 19]
var copiedAges = ages  
copiedAges["Peter"] = 24
println(ages["Peter"])
// prints "23" 

If you assign an Array instance to a constant or variable, or pass an Array instance as an argument to a function or method call, the contents of the array are not copied at the point that the assignment or call takes place. Instead, both arrays share the same sequence of element values. When you modify an element value through one array, the result is observable through the other.

For arrays, copying only takes place when you perform an action that has the potential to modify the length of the array. This includes appending, inserting, or removing items, or using a ranged subscript to replace a range of items in the array.

var a = [1, 2, 3]
var b = a
var c = a

println(a[0])
// 1
println(b[0])
// 1
println(c[0])
// 1

a[0] = 42
println(a[0])
// 42
println(b[0])
// 42
println(c[0])
// 42

a.append(4)
a[0] = 777
println(a[0])
// 777
println(b[0])
// 42
println(c[0])
// 42

b.unshare()

b[0] = -105
println(a[0])
// 777
println(b[0])
// -105
println(c[0])
// 42

if b === c {
    println("b and c still share the same array elements.")
} else {
    println("b and c now refer to two independent sets of array elements.")
}
// prints "b and c now refer to two independent sets of array elements."       
var names = ["Mohsen", "Hilary", "Justyn", "Amy", "Rich", "Graham", "Vic"]
var copiedNames = names.copy()
copiedNames[0] = "Mo"
println(names[0])
// prints "Mohsen"  

If you simply need to be sure that your reference to an array’s contents is the only reference in existence, call the unshare method, not the copy method. The unshare method does not make a copy of the array unless it is necessary to do so. The copy method always copies the array, even if it is already unshared.

Properties

Computed properties are provided by classes, structures, and enumerations. Stored properties are provided only by classes and structures.

let rangeOfFourItems = FixedLengthRange(firstValue: 0, length: 4)
// this range represents integer values 0, 1, 2, and 3
rangeOfFourItems.firstValue = 6
// this will report an error, even thought firstValue is a variable property 

Because rangeOfFourItems is declared as a constant (with the let keyword), it is not possible to change its firstValue property, even though firstValue is a variable property.

This behavior is due to structures being value types. When an instance of a value type is marked as a constant, so are all of its properties.

The same is not true for classes, which are reference types. If you assign an instance of a reference type to a constant, you can still change that instance’s variable properties.

class DataImporter {
    /*
    DataImporter is a class to import data from an external file.
    The class is assumed to take a non-trivial amount of time to initialize.
    */
    var fileName = "data.txt"
    // the DataImporter class would provide data importing functionality here
}

class DataManager {
    @lazy var importer = DataImporter()
    var data = String[]()
    // the DataManager class would provide data management functionality here
}

let manager = DataManager()
manager.data += "Some data"
manager.data += "Some more data"
// the DataImporter instance for the importer property has not yet been created

println(manager.importer.fileName)
// the DataImporter instance for the importer property has now been created
// prints "data.txt"  

In addition to stored properties, classes, structures, and enumerations can define computed properties, which do not actually store a value. Instead, they provide a getter and an optional setter to retrieve and set other properties and values indirectly.

struct Point {
    var x = 0.0, y = 0.0
}
struct Size {
    var width = 0.0, height = 0.0
}
struct Rect {
    var origin = Point()
    var size = Size()
    var center: Point { // center是computed property
    get {
        let centerX = origin.x + (size.width / 2)
        let centerY = origin.y + (size.height / 2)
        return Point(x: centerX, y: centerY)
    }
    set(newCenter) {
        origin.x = newCenter.x - (size.width / 2)
        origin.y = newCenter.y - (size.height / 2)
    }
    }
}
var square = Rect(origin: Point(x: 0.0, y: 0.0),
    size: Size(width: 10.0, height: 10.0))
let initialSquareCenter = square.center
square.center = Point(x: 15.0, y: 15.0)
println("square.origin is now at (\(square.origin.x), \(square.origin.y))")
// prints "square.origin is now at (10.0, 10.0)" 

You must declare computed properties—including read-only computed properties—as variable properties with the var keyword, because their value is not fixed.

struct Cuboid {
    var width = 0.0, height = 0.0, depth = 0.0
    var volume: Double {
    return width * height * depth
    }
}
let fourByFiveByTwo = Cuboid(width: 4.0, height: 5.0, depth: 2.0)
println("the volume of fourByFiveByTwo is \(fourByFiveByTwo.volume)")
// prints "the volume of fourByFiveByTwo is 40.0” 

willSet and didSet observers are not called when a property is first initialized. They are only called when the property’s value is set outside of an initialization context.

class StepCounter {
    var totalSteps: Int = 0 {
    willSet(newTotalSteps) {
        println("About to set totalSteps to \(newTotalSteps)")
    }
    didSet {
        if totalSteps > oldValue  {
            println("Added \(totalSteps - oldValue) steps")
        }
    }
    }
}
let stepCounter = StepCounter()
stepCounter.totalSteps = 200
// About to set totalSteps to 200
// Added 200 steps
stepCounter.totalSteps = 360
// About to set totalSteps to 360
// Added 160 steps
stepCounter.totalSteps = 896
// About to set totalSteps to 896
// Added 536 steps 

If you assign a value to a property within its own didSet observer, the new value that you assign will replace the one that was just set.

Global constants and variables are always computed lazily, in a similar manner to Lazy Stored Properties. Unlike lazy stored properties, global constants and variables do not need to be marked with the @lazy attribute. Local constants and variables are never computed lazily.

For value types (that is, structures and enumerations), you can define stored and computed type properties. For classes, you can define computed type properties only.

Unlike stored instance properties, you must always give stored type properties a default value. This is because the type itself does not have an initializer that can assign a value to a stored type property at initialization time.

struct SomeStructure {
    static var storedTypeProperty = "Some value."
    static var computedTypeProperty: Int {
    // return an Int value here
    }
}
enum SomeEnumeration {
    static var storedTypeProperty = "Some value."
    static var computedTypeProperty: Int {
    // return an Int value here
    }
}
class SomeClass {
    class var computedTypeProperty: Int {
    // return an Int value here
    }
} 

println(SomeClass.computedTypeProperty)
// prints "42"

println(SomeStructure.storedTypeProperty)
// prints "Some value."
SomeStructure.storedTypeProperty = "Another value."
println(SomeStructure.storedTypeProperty)
// prints "Another value." 
struct AudioChannel {
    static let thresholdLevel = 10
    static var maxInputLevelForAllChannels = 0
    var currentLevel: Int = 0 {
    didSet {
        if currentLevel > AudioChannel.thresholdLevel {
            // cap the new audio level to the threshold level
            currentLevel = AudioChannel.thresholdLevel
        }
        if currentLevel > AudioChannel.maxInputLevelForAllChannels {
            // store this as the new overall maximum input level
            AudioChannel.maxInputLevelForAllChannels = currentLevel
        }
    }
    }
}

var leftChannel = AudioChannel()
var rightChannel = AudioChannel()

leftChannel.currentLevel = 7
println(leftChannel.currentLevel)
// prints "7"
println(AudioChannel.maxInputLevelForAllChannels)
// prints “7"

rightChannel.currentLevel = 11
println(rightChannel.currentLevel)
// prints "10"
println(AudioChannel.maxInputLevelForAllChannels)
// prints "10"    

Methods

Structures and enumerations are value types. By default, the properties of a value type cannot be modified from within its instance methods.

struct Point {
    var x = 0.0, y = 0.0
    mutating func moveByX(deltaX: Double, y deltaY: Double) {
        x += deltaX
        y += deltaY
    }
}
var somePoint = Point(x: 1.0, y: 1.0)
somePoint.moveByX(2.0, y: 3.0)
println("The point is now at (\(somePoint.x), \(somePoint.y))")
// prints "The point is now at (3.0, 4.0)" 
let fixedPoint = Point(x: 3.0, y: 3.0)
fixedPoint.moveByX(2.0, y: 3.0)
// this will report an error 
enum TriStateSwitch {
    case Off, Low, High
    mutating func next() {
        switch self {
        case Off:
            self = Low
        case Low:
            self = High
        case High:
            self = Off
        }
    }
}
var ovenLight = TriStateSwitch.Low
ovenLight.next()
// ovenLight is now equal to .High
ovenLight.next()
// ovenLight is now equal to .Off 
struct LevelTracker {
    static var highestUnlockedLevel = 1
    static func unlockLevel(level: Int) {
        if level > highestUnlockedLevel { highestUnlockedLevel = level }
    }
    static func levelIsUnlocked(level: Int) -> Bool {
        return level <= highestUnlockedLevel
    }
    var currentLevel = 1
    mutating func advanceToLevel(level: Int) -> Bool {
        if LevelTracker.levelIsUnlocked(level) {
            currentLevel = level
            return true
        } else {
            return false
        }
    }
}

class Player {
    var tracker = LevelTracker()
    let playerName: String
    func completedLevel(level: Int) {
        LevelTracker.unlockLevel(level + 1)
        tracker.advanceToLevel(level + 1)
    }
    init(name: String) {
        playerName = name
    }
}

var player = Player(name: "Argyrios")
player.completedLevel(1)
println("highest unlocked level is now \(LevelTracker.highestUnlockedLevel)")
// prints "highest unlocked level is now 2”

player = Player(name: "Beto")
if player.tracker.advanceToLevel(6) {
    println("player is now on level 6")
} else {
    println("level 6 has not yet been unlocked")
}
// prints "level 6 has not yet been unlocked"    

Subscripts

subscript(index: Int) -> Int {
    get {
        // return an appropriate subscript value here
    }
    set(newValue) {
        // perform a suitable setting action here
    }
}

// read-only subscript
subscript(index: Int) -> Int {
    // return an appropriate subscript value here
}

struct TimesTable {
    let multiplier: Int
    subscript(index: Int) -> Int {
        return multiplier * index
    }
}
let threeTimesTable = TimesTable(multiplier: 3)
println("six times three is \(threeTimesTable[6])")
// prints "six times three is 18" 
struct Matrix {
    let rows: Int, columns: Int
    var grid: Double[]
    init(rows: Int, columns: Int) {
        self.rows = rows
        self.columns = columns
        grid = Array(count: rows * columns, repeatedValue: 0.0)
    }
    func indexIsValidForRow(row: Int, column: Int) -> Bool {
        return row >= 0 && row < rows && column >= 0 && column < columns
    }
    subscript(row: Int, column: Int) -> Double {
        get {
            assert(indexIsValidForRow(row, column: column), "Index out of range")
            return grid[(row * columns) + column]
        }
        set {
            assert(indexIsValidForRow(row, column: column), "Index out of range")
            grid[(row * columns) + column] = newValue
        }
    }
}

var matrix = Matrix(rows: 2, columns: 2)
matrix[0, 1] = 1.5
matrix[1, 0] = 3.2

let someValue = matrix[2, 2]
// this triggers an assert, because [2, 2] is outside of the matrix bounds    

Inheritance

Swift classes do not inherit from a universal base class. Classes you define without specifying a superclass automatically become base classes for you to build upon.

class Car: Vehicle {
    var speed: Double = 0.0
    init() {
        super.init()
        maxPassengers = 5
        numberOfWheels = 4
    }
    override func description() -> String {
        return super.description() + "; "
            + "traveling at \(speed) mph"
    }
} 

You can present an inherited read-only property as a read-write property by providing both a getter and a setter in your subclass property override. You cannot, however, present an inherited read-write property as a read-only property.

You can prevent a method, property, or subscript from being overridden by marking it as final

Initialization

Classes and structures must set all of their stored properties to an appropriate initial value by the time an instance of that class or structure is created. Stored properties cannot be left in an indeterminate state.

Swift provides an automatic external name for every parameter in an initializer if you don’t provide an external name yourself. This automatic external name is the same as the local name, as if you had written a hash symbol before every initialization parameter.

If you do not want to provide an external name for a parameter in an initializer, provide an underscore (_) as an explicit external name for that parameter to override the default behavior described above.

struct Color {
    let red = 0.0, green = 0.0, blue = 0.0
    init(red: Double, green: Double, blue: Double) {
        self.red   = red
        self.green = green
        self.blue  = blue
    }
}

let magenta = Color(red: 1.0, green: 0.0, blue: 1.0)  

let veryGreen = Color(0.0, 1.0, 0.0)
// this reports a compile-time error - external names are required 

You can modify the value of a constant property at any point during initialization, as long as it is set to a definite value by the time initialization finishes.

class SurveyQuestion {
    let text: String
    var response: String?
    init(text: String) {
        self.text = text
    }
    func ask() {
        println(text)
    }
}
let beetsQuestion = SurveyQuestion(text: "How about beets?")
beetsQuestion.ask()
// prints "How about beets?"
beetsQuestion.response = "I also like beets. (But not with cheese.)" 

structure types automatically receive a memberwise initializer if they provide default values for all of their stored properties and do not define any of their own custom initializers.

struct Size {
    var width = 0.0, height = 0.0
}
let twoByTwo = Size(width: 2.0, height: 2.0) 

If you want your custom value type to be initializable with the default initializer and memberwise initializer, and also with your own custom initializers, write your custom initializers in an extension rather than as part of the value type’s original implementation.

Designated initializers are the primary initializers for a class. A designated initializer fully initializes all properties introduced by that class and calls an appropriate superclass initializer to continue the initialization process up the superclass chain.

Convenience initializers are secondary, supporting initializers for a class. You can define a convenience initializer to call a designated initializer from the same class as the convenience initializer with some of the designated initializer’s parameters set to default values. You can also define a convenience initializer to create an instance of that class for a specific use case or input value type.

To simplify the relationships between designated and convenience initializers, Swift applies the following three rules for delegation calls between initializers:

Rule 1: Designated initializers must call a designated initializer from their immediate superclass.

Rule 2: Convenience initializers must call another initializer available in the same class.

Rule 3: Convenience initializers must ultimately end up calling a designated initializer.

A simple way to remember this is:

Designated initializers must always delegate up. Convenience initializers must always delegate across.

Class initialization in Swift is a two-phase process. In the first phase, each stored property is assigned an initial value by the class that introduced it. Once the initial state for every stored property has been determined, the second phase begins, and each class is given the opportunity to customize its stored properties further before the new instance is considered ready for use.

class Food {
    var name: String
    init(name: String) {
        self.name = name
    }
    convenience init() {
        self.init(name: "[Unnamed]")
    }
} 

let namedMeat = Food(name: "Bacon")
// namedMeat's name is “Bacon"

let mysteryMeat = Food()
// mysteryMeat's name is "[Unnamed]”  

class RecipeIngredient: Food {
    var quantity: Int
    init(name: String, quantity: Int) {
        self.quantity = quantity
        super.init(name: name)
    }
    convenience init(name: String) {
        self.init(name: name, quantity: 1)
    }
}

let oneMysteryItem = RecipeIngredient()
let oneBacon = RecipeIngredient(name: "Bacon")
let sixEggs = RecipeIngredient(name: "Eggs", quantity: 6)

class ShoppingListItem: RecipeIngredient {
    var purchased = false
    var description: String {
    var output = "\(quantity) x \(name.lowercaseString)"
        output += purchased ? " ✔" : " ✘"
        return output
    }
}

var breakfastList = [
    ShoppingListItem(),
    ShoppingListItem(name: "Bacon"),
    ShoppingListItem(name: "Eggs", quantity: 6),
]
breakfastList[0].name = "Orange juice"
breakfastList[0].purchased = true
for item in breakfastList {
    println(item.description)
}
// 1 x orange juice ✔
// 1 x bacon ✘
// 6 x eggs ✘    
class SomeClass {
    let someProperty: SomeType = {
        // create a default value for someProperty inside this closure
        // someValue must be of the same type as SomeType
        return someValue
        }()
}

Note that the closure’s end curly brace is followed by an empty pair of parentheses. This tells Swift to execute the closure immediately.

struct Checkerboard {
    let boardColors: Bool[] = {
        var temporaryBoard = Bool[]()
        var isBlack = false
        for i in 1...10 {
            for j in 1...10 {
                temporaryBoard.append(isBlack)
                isBlack = !isBlack
            }
            isBlack = !isBlack
        }
        return temporaryBoard
        }()
    func squareIsBlackAtRow(row: Int, column: Int) -> Bool {
        return boardColors[(row * 10) + column]
    }
}

let board = Checkerboard()
println(board.squareIsBlackAtRow(0, column: 1))
// prints "true"
println(board.squareIsBlackAtRow(9, column: 9))
// prints "false"  

Deinitialization

Deinitializers are only available on class types.

deinit {
    // perform the deinitialization
} 
struct Bank {
    static var coinsInBank = 10_000
    static func vendCoins(var numberOfCoinsToVend: Int) -> Int {
        numberOfCoinsToVend = min(numberOfCoinsToVend, coinsInBank)
        coinsInBank -= numberOfCoinsToVend
        return numberOfCoinsToVend
    }
    static func receiveCoins(coins: Int) {
        coinsInBank += coins
    }
}

lass Player {
    var coinsInPurse: Int
    init(coins: Int) {
        coinsInPurse = Bank.vendCoins(coins)
    }
    func winCoins(coins: Int) {
        coinsInPurse += Bank.vendCoins(coins)
    }
    deinit {
        Bank.receiveCoins(coinsInPurse)
    }
}

var playerOne: Player? = Player(coins: 100)
println("A new player has joined the game with \(playerOne!.coinsInPurse) coins")
// prints "A new player has joined the game with 100 coins"
println("There are now \(Bank.coinsInBank) coins left in the bank")
// prints "There are now 9900 coins left in the bank”

playerOne!.winCoins(2_000)
println("PlayerOne won 2000 coins & now has \(playerOne!.coinsInPurse) coins")
// prints "PlayerOne won 2000 coins & now has 2100 coins"
println("The bank now only has \(Bank.coinsInBank) coins left")
// prints "The bank now only has 7900 coins left”

playerOne = nil
println("PlayerOne has left the game")
// prints "PlayerOne has left the game"
println("The bank now has \(Bank.coinsInBank) coins")
// prints "The bank now has 10000 coins"     

Automatic Reference Counting

class Person {
    let name: String
    init(name: String) { self.name = name }
    var apartment: Apartment?
    deinit { println("\(name) is being deinitialized") }
}

class Apartment {
    let number: Int
    init(number: Int) { self.number = number }
    var tenant: Person?
    deinit { println("Apartment #\(number) is being deinitialized") }
}

var john: Person?
var number73: Apartment?

john = Person(name: "John Appleseed")
number73 = Apartment(number: 73)

john!.apartment = number73
number73!.tenant = john    

Resolving Strong Reference Cycles Between Class Instances: Weak References

class Person {
    let name: String
    init(name: String) { self.name = name }
    var apartment: Apartment?
    deinit { println("\(name) is being deinitialized") }
}

class Apartment {
    let number: Int
    init(number: Int) { self.number = number }
    weak var tenant: Person?
    deinit { println("Apartment #\(number) is being deinitialized") }
}

var john: Person?
var number73: Apartment?

john = Person(name: "John Appleseed")
number73 = Apartment(number: 73)

john!.apartment = number73
number73!.tenant = john  

Resolving Strong Reference Cycles Between Class Instances: Unowned References

class Customer {
    let name: String
    var card: CreditCard?
    init(name: String) {
        self.name = name
    }
    deinit { println("\(name) is being deinitialized") }
}

class CreditCard {
    let number: Int
    unowned let customer: Customer
    init(number: Int, customer: Customer) {
        self.number = number
        self.customer = customer
    }
    deinit { println("Card #\(number) is being deinitialized") }
}

var john: Customer?
john = Customer(name: "John Appleseed")
john!.card = CreditCard(number: 1234_5678_9012_3456, customer: john!)   

Unowned References and Implicitly Unwrapped Optional Properties

class Country {
    let name: String
    let capitalCity: City!
    init(name: String, capitalName: String) {
        self.name = name
        self.capitalCity = City(name: capitalName, country: self)
    }
}

class City {
    let name: String
    unowned let country: Country
    init(name: String, country: Country) {
        self.name = name
        self.country = country
    }
} 

var country = Country(name: "Canada", capitalName: "Ottawa")
println("\(country.name)'s capital city is called \(country.capitalCity.name)")
// prints "Canada's capital city is called Ottawa" 

The initializer for City is called from within the initializer for Country. However, the initializer for Country cannot pass self to the City initializer until a new Country instance is fully initialized, as described in Two-Phase Initialization.

To cope with this requirement, you declare the capitalCity property of Country as an implicitly unwrapped optional property, indicated by the exclamation mark at the end of its type annotation (City!). This means that the capitalCity property has a default value of nil, like any other optional, but can be accessed without the need to unwrap its value as described in Implicitly Unwrapped Optionals.

Resolving Strong Reference Cycles for Closures

class HTMLElement {

    let name: String
    let text: String?

    @lazy var asHTML: () -> String = {
        if let text = self.text {
            return "<\(self.name)>\(text)</\(self.name)>"
        } else {
            return "<\(self.name) />"
        }
    }

    init(name: String, text: String? = nil) {
        self.name = name
        self.text = text
    }

    deinit {
        println("\(name) is being deinitialized")
    }

} 

var paragraph: HTMLElement? = HTMLElement(name: "p", text: "hello, world")
println(paragraph!.asHTML())
// prints "<p>hello, world</p>” 
paragraph = nil  // the message in the HTMLElement deinitializer is not printed 
class HTMLElement {

    let name: String
    let text: String?

    @lazy var asHTML: () -> String = {
        [unowned self] in
        if let text = self.text {
            return "<\(self.name)>\(text)</\(self.name)>"
        } else {
            return "<\(self.name) />"
        }
    }

    init(name: String, text: String? = nil) {
        self.name = name
        self.text = text
    }

    deinit {
        println("\(name) is being deinitialized")
    }

}

var paragraph: HTMLElement? = HTMLElement(name: "p", text: "hello, world")
println(paragraph!.asHTML())
// prints "<p>hello, world</p>”

paragraph = nil
// prints "p is being deinitialized"   

Optional Chaining

You specify optional chaining by placing a question mark (?) after the optional value on which you wish to call a property, method or subscript if the optional is non-nil.

class Person {
    var residence: Residence?
}

class Residence {
    var numberOfRooms = 1
}

let john = Person()  
let roomCount = john.residence!.numberOfRooms
// this triggers a runtime error

if let roomCount = john.residence?.numberOfRooms { // 返回的是Int?
    println("John's residence has \(roomCount) room(s).")
} else {
    println("Unable to retrieve the number of rooms.")
}
// prints "Unable to retrieve the number of rooms.”

john.residence = Residence()
if let roomCount = john.residence?.numberOfRooms {
    println("John's residence has \(roomCount) room(s).")
} else {
    println("Unable to retrieve the number of rooms.")
}
// prints "John's residence has 1 room(s)."    

The fact that it is queried through an optional chain means that the call to numberOfRooms will always return an Int? instead of an Int.

You cannot set a property’s value through optional chaining.

if john.residence?.printNumberOfRooms() {
    println("It was possible to print the number of rooms.")
} else {
    println("It was not possible to print the number of rooms.")
}
// prints "It was not possible to print the number of rooms.”

if let firstRoomName = john.residence?[0].name {
    println("The first room name is \(firstRoomName).")
} else {
    println("Unable to retrieve the first room name.")
}
// prints "Unable to retrieve the first room name."

If you try to retrieve an Int value through optional chaining, an Int? is always returned, no matter how many levels of chaining are used. Similarly, if you try to retrieve an Int? value through optional chaining, an Int? is always returned, no matter how many levels of chaining are used.

Type Casting

Type casting in Swift is implemented with the is and as operators. These two operators provide a simple and expressive way to check the type of a value or cast a value to a different type.

class MediaItem {
    var name: String
    init(name: String) {
        self.name = name
    }
}

class Movie: MediaItem {
    var director: String
    init(name: String, director: String) {
        self.director = director
        super.init(name: name)
    }
}

class Song: MediaItem {
    var artist: String
    init(name: String, artist: String) {
        self.artist = artist
        super.init(name: name)
    }
}

let library = [
    Movie(name: "Casablanca", director: "Michael Curtiz"),
    Song(name: "Blue Suede Shoes", artist: "Elvis Presley"),
    Movie(name: "Citizen Kane", director: "Orson Welles"),
    Song(name: "The One And Only", artist: "Chesney Hawkes"),
    Song(name: "Never Gonna Give You Up", artist: "Rick Astley")
]
// the type of "library" is inferred to be MediaItem[]

// Use the type check operator (is) to check whether an instance is of a certain subclass type. 

var movieCount = 0
var songCount = 0

for item in library {
    if item is Movie {
        ++movieCount
    } else if item is Song {
        ++songCount
    }
}

println("Media library contains \(movieCount) movies and \(songCount) songs")
// prints "Media library contains 2 movies and 3 songs”

for item in library {
    if let movie = item as? Movie {
        println("Movie: '\(movie.name)', dir. \(movie.director)")
    } else if let song = item as? Song {
        println("Song: '\(song.name)', by \(song.artist)")
    }
}

// Movie: 'Casablanca', dir. Michael Curtiz
// Song: 'Blue Suede Shoes', by Elvis Presley
// Movie: 'Citizen Kane', dir. Orson Welles
// Song: 'The One And Only', by Chesney Hawkes
// Song: 'Never Gonna Give You Up', by Rick Astley     

Casting does not actually modify the instance or change its values. The underlying instance remains the same; it is simply treated and accessed as an instance of the type to which it has been cast.

AnyObject can represent an instance of any class type. Any can represent an instance of any type at all, apart from function types.

let someObjects: AnyObject[] = [
    Movie(name: "2001: A Space Odyssey", director: "Stanley Kubrick"),
    Movie(name: "Moon", director: "Duncan Jones"),
    Movie(name: "Alien", director: "Ridley Scott")
]

for object in someObjects {
    let movie = object as Movie
    println("Movie: '\(movie.name)', dir. \(movie.director)")
}
// Movie: '2001: A Space Odyssey', dir. Stanley Kubrick
// Movie: 'Moon', dir. Duncan Jones
// Movie: 'Alien', dir. Ridley Scott

for movie in someObjects as Movie[] {
    println("Movie: '\(movie.name)', dir. \(movie.director)")
}
// Movie: '2001: A Space Odyssey', dir. Stanley Kubrick
// Movie: 'Moon', dir. Duncan Jones
// Movie: 'Alien', dir. Ridley Scott   
var things = Any[]()

things.append(0)
things.append(0.0)
things.append(42)
things.append(3.14159)
things.append("hello")
things.append((3.0, 5.0))
things.append(Movie(name: "Ghostbusters", director: "Ivan Reitman”))

for thing in things {
    switch thing {
    case 0 as Int:
        println("zero as an Int")
    case 0 as Double:
        println("zero as a Double")
    case let someInt as Int:
        println("an integer value of \(someInt)")
    case let someDouble as Double where someDouble > 0:
        println("a positive double value of \(someDouble)")
    case is Double:
        println("some other double value that I don't want to print")
    case let someString as String:
        println("a string value of \"\(someString)\"")
    case let (x, y) as (Double, Double):
        println("an (x, y) point at \(x), \(y)")
    case let movie as Movie:
        println("a movie called '\(movie.name)', dir. \(movie.director)")
    default:
        println("something else")
    }
}

// zero as an Int
// zero as a Double
// an integer value of 42
// a positive double value of 3.14159
// a string value of "hello"
// an (x, y) point at 3.0, 5.0
// a movie called 'Ghostbusters', dir. Ivan Reitman  

Nested Types

struct BlackjackCard {

    // nested Suit enumeration
    enum Suit: Character {
        case Spades = "♠", Hearts = "♡", Diamonds = "♢", Clubs = "♣"
    }

    // nested Rank enumeration
    enum Rank: Int {
        case Two = 2, Three, Four, Five, Six, Seven, Eight, Nine, Ten
        case Jack, Queen, King, Ace
        struct Values {
            let first: Int, second: Int?
        }
        var values: Values {
        switch self {
        case .Ace:
            return Values(first: 1, second: 11)
        case .Jack, .Queen, .King:
            return Values(first: 10, second: nil)
        default:
            return Values(first: self.toRaw(), second: nil)
            }
        }
    }

    // BlackjackCard properties and methods
    let rank: Rank, suit: Suit
    var description: String {
    var output = "suit is \(suit.toRaw()),"
        output += " value is \(rank.values.first)"
        if let second = rank.values.second {
            output += " or \(second)"
        }
        return output
    }
}

let theAceOfSpades = BlackjackCard(rank: .Ace, suit: .Spades)
println("theAceOfSpades: \(theAceOfSpades.description)")
// prints "theAceOfSpades: suit is ♠, value is 1 or 11”

let heartsSymbol = BlackjackCard.Suit.Hearts.toRaw()
// heartsSymbol is "♡"   

Extensions

Extensions are similar to categories in Objective-C.

Extensions in Swift can:

Add computed properties and computed static properties Define instance methods and type methods Provide new initializers Define subscripts Define and use new nested types Make an existing type conform to a protocol

If you define an extension to add new functionality to an existing type, the new functionality will be available on all existing instances of that type, even if they were created before the extension was defined.

extension SomeType {
    // new functionality to add to SomeType goes here
}

extension SomeType: SomeProtocol, AnotherProtocol {
    // implementation of protocol requirements goes here
}  
extension Double {
    var km: Double { return self * 1_000.0 }
    var m: Double { return self }
    var cm: Double { return self / 100.0 }
    var mm: Double { return self / 1_000.0 }
    var ft: Double { return self / 3.28084 }
}
let oneInch = 25.4.mm
println("One inch is \(oneInch) meters")
// prints "One inch is 0.0254 meters"
let threeFeet = 3.ft
println("Three feet is \(threeFeet) meters")
// prints "Three feet is 0.914399970739201 meters" 

Extensions can add new computed properties, but they cannot add stored properties, or add property observers to existing properties.

struct Size {
    var width = 0.0, height = 0.0
}
struct Point {
    var x = 0.0, y = 0.0
}
struct Rect {
    var origin = Point()
    var size = Size()
}

let defaultRect = Rect()
let memberwiseRect = Rect(origin: Point(x: 2.0, y: 2.0),
    size: Size(width: 5.0, height: 5.0))

extension Rect {
    init(center: Point, size: Size) {
        let originX = center.x - (size.width / 2)
        let originY = center.y - (size.height / 2)
        self.init(origin: Point(x: originX, y: originY), size: size)
    }
}

let centerRect = Rect(center: Point(x: 4.0, y: 4.0),
    size: Size(width: 3.0, height: 3.0))
// centerRect's origin is (2.5, 2.5) and its size is (3.0, 3.0)    
extension Int {
    func repetitions(task: () -> ()) {
        for i in 0..self {
            task()
        }
    }
}

3.repetitions({
    println("Hello!")
    })
// Hello!
// Hello!
// Hello!

//Use trailing closure syntax to make the call more succinct:
3.repetitions {
    println("Goodbye!")
}
// Goodbye!
// Goodbye!
// Goodbye!   

// Structure and enumeration methods that modify self or its properties must mark the instance method as mutating, just like mutating methods from an original implementation.

extension Int {
    mutating func square() {
        self = self * self
    }
}
var someInt = 3
someInt.square()
// someInt is now 9 
extension Int {
    subscript(digitIndex: Int) -> Int {
        var decimalBase = 1
            for _ in 1...digitIndex {
                decimalBase *= 10
            }
            return (self / decimalBase) % 10
    }
}
746381295[0]
// returns 5
746381295[1]
// returns 9
746381295[2]
// returns 2
746381295[8]
// returns 7 
746381295[9]
// returns 0, as if you had requested:
0746381295[9] 
extension Character {
    enum Kind {
        case Vowel, Consonant, Other
    }
    var kind: Kind {
    switch String(self).lowercaseString {
    case "a", "e", "i", "o", "u":
        return .Vowel
    case "b", "c", "d", "f", "g", "h", "j", "k", "l", "m",
    "n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z":
        return .Consonant
    default:
        return .Other
        }
    }
}

func printLetterKinds(word: String) {
    println("'\(word)' is made up of the following kinds of letters:")
    for character in word {
        switch character.kind {
        case .Vowel:
            print("vowel ")
        case .Consonant:
            print("consonant ")
        case .Other:
            print("other ")
        }
    }
    print("\n")
}
printLetterKinds("Hello")
// 'Hello' is made up of the following kinds of letters:
// consonant vowel consonant consonant vowel  

NOTE: character.kind is already known to be of type Character.Kind. Because of this, all of the Character.Kind member values can be written in shorthand form inside the switch statement, such as .Vowel rather than Character.Kind.Vowel.

Protocols

A protocol defines a blueprint of methods, properties, and other requirements that suit a particular task or piece of functionality. The protocol doesn’t actually provide an implementation for any of these requirements—it only describes what an implementation will look like. The protocol can then be adopted by a class, structure, or enumeration to provide an actual implementation of those requirements. Any type that satisfies the requirements of a protocol is said to conform to that protocol.

protocol SomeProtocol {
    // protocol definition goes here
}

struct SomeStructure: FirstProtocol, AnotherProtocol {
    // structure definition goes here
}

class SomeClass: SomeSuperclass, FirstProtocol, AnotherProtocol {
    // class definition goes here
}
protocol SomeProtocol {
    var mustBeSettable: Int { get set }
    var doesNotNeedToBeSettable: Int { get }
}

// Always prefix type property requirements with the class keyword when you define them in a protocol.
protocol AnotherProtocol {
    class var someTypeProperty: Int { get set }
}
protocol FullyNamed {
    var fullName: String { get }
}

struct Person: FullyNamed {
    var fullName: String
}
let john = Person(fullName: "John Appleseed")
// john.fullName is "John Appleseed”

class Starship: FullyNamed {
    var prefix: String?
    var name: String
    init(name: String, prefix: String? = nil) {
        self.name = name
        self.prefix = prefix
    }
    var fullName: String {
    return (prefix ? prefix! + " " : "") + name
    }
}
var ncc1701 = Starship(name: "Enterprise", prefix: "USS")
// ncc1701.fullName is "USS Enterprise"   

Protocols use the same syntax as normal methods, but are not allowed to specify default values for method parameters.

protocol SomeProtocol {
    class func someTypeMethod()
}

protocol RandomNumberGenerator {
    func random() -> Double
}

class LinearCongruentialGenerator: RandomNumberGenerator {
    var lastRandom = 42.0
    let m = 139968.0
    let a = 3877.0
    let c = 29573.0
    func random() -> Double {
        lastRandom = ((lastRandom * a + c) % m)
        return lastRandom / m
    }
}
let generator = LinearCongruentialGenerator()
println("Here's a random number: \(generator.random())")
// prints "Here's a random number: 0.37464991998171"
println("And another one: \(generator.random())")
// prints "And another one: 0.729023776863283"   

If you mark a protocol instance method requirement as mutating, you do not need to write the mutating keyword when writing an implementation of that method for a class. The mutating keyword is only used by structures and enumerations.

protocol Togglable {
    mutating func toggle()
}

enum OnOffSwitch: Togglable {
    case Off, On
    mutating func toggle() {
        switch self {
        case Off:
            self = On
        case On:
            self = Off
        }
    }
}
var lightSwitch = OnOffSwitch.Off
lightSwitch.toggle()
// lightSwitch is now equal to .On  
class Dice {
    let sides: Int
    let generator: RandomNumberGenerator
    init(sides: Int, generator: RandomNumberGenerator) {
        self.sides = sides
        self.generator = generator
    }
    func roll() -> Int {
        return Int(generator.random() * Double(sides)) + 1
    }
}

var d6 = Dice(sides: 6, generator: LinearCongruentialGenerator())
for _ in 1...5 {
    println("Random dice roll is \(d6.roll())")
}
// Random dice roll is 3
// Random dice roll is 5
// Random dice roll is 4
// Random dice roll is 5
// Random dice roll is 4  
protocol DiceGame {
    var dice: Dice { get }
    func play()
}
protocol DiceGameDelegate {
    func gameDidStart(game: DiceGame)
    func game(game: DiceGame, didStartNewTurnWithDiceRoll diceRoll: Int)
    func gameDidEnd(game: DiceGame)
}

class SnakesAndLadders: DiceGame {
    let finalSquare = 25
    let dice = Dice(sides: 6, generator: LinearCongruentialGenerator())
    var square = 0
    var board: Int[]
    init() {
        board = Int[](count: finalSquare + 1, repeatedValue: 0)
        board[03] = +08; board[06] = +11; board[09] = +09; board[10] = +02
        board[14] = -10; board[19] = -11; board[22] = -02; board[24] = -08
    }
    var delegate: DiceGameDelegate?
    func play() {
        square = 0
        delegate?.gameDidStart(self)
        gameLoop: while square != finalSquare {
            let diceRoll = dice.roll()
            delegate?.game(self, didStartNewTurnWithDiceRoll: diceRoll)
            switch square + diceRoll {
            case finalSquare:
                break gameLoop
            case let newSquare where newSquare > finalSquare:
                continue gameLoop
            default:
                square += diceRoll
                square += board[square]
            }
        }
        delegate?.gameDidEnd(self)
    }
}

class DiceGameTracker: DiceGameDelegate {
    var numberOfTurns = 0
    func gameDidStart(game: DiceGame) {
        numberOfTurns = 0
        if game is SnakesAndLadders {
            println("Started a new game of Snakes and Ladders")
        }
        println("The game is using a \(game.dice.sides)-sided dice")
    }
    func game(game: DiceGame, didStartNewTurnWithDiceRoll diceRoll: Int) {
        ++numberOfTurns
        println("Rolled a \(diceRoll)")
    }
    func gameDidEnd(game: DiceGame) {
        println("The game lasted for \(numberOfTurns) turns")
    }
}

let tracker = DiceGameTracker()
let game = SnakesAndLadders()
game.delegate = tracker
game.play()
// Started a new game of Snakes and Ladders
// The game is using a 6-sided dice
// Rolled a 3
// Rolled a 5
// Rolled a 4
// Rolled a 5
// The game lasted for 4 turns    
protocol TextRepresentable {
    func asText() -> String
}

extension Dice: TextRepresentable {
    func asText() -> String {
        return "A \(sides)-sided dice"
    }
}

let d12 = Dice(sides: 12, generator: LinearCongruentialGenerator())
println(d12.asText())
// prints "A 12-sided dice”

extension SnakesAndLadders: TextRepresentable {
    func asText() -> String {
        return "A game of Snakes and Ladders with \(finalSquare) squares"
    }
}
println(game.asText())
// prints "A game of Snakes and Ladders with 25 squares"    

If a type already conforms to all of the requirements of a protocol, but has not yet stated that it adopts that protocol, you can make it adopt the protocol with an empty extension:

struct Hamster {
    var name: String
    func asText() -> String {
        return "A hamster named \(name)"
    }
}
extension Hamster: TextRepresentable {} 

let simonTheHamster = Hamster(name: "Simon")
let somethingTextRepresentable: TextRepresentable = simonTheHamster
println(somethingTextRepresentable.asText())
// prints "A hamster named Simon" 
let things: TextRepresentable[] = [game, d12, simonTheHamster]

for thing in things {
    println(thing.asText())
}
// A game of Snakes and Ladders with 25 squares
// A 12-sided dice
// A hamster named Simon  
protocol InheritingProtocol: SomeProtocol, AnotherProtocol {
    // protocol definition goes here
}

protocol PrettyTextRepresentable: TextRepresentable {
    func asPrettyText() -> String
}

extension SnakesAndLadders: PrettyTextRepresentable {
    func asPrettyText() -> String {
        var output = asText() + ":\n"
        for index in 1...finalSquare {
            switch board[index] {
            case let ladder where ladder > 0:
                output += "▲ "
            case let snake where snake < 0:
                output += "▼ "
            default:
                output += "○ "
            }
        }
        return output
    }
}

println(game.asPrettyText())
// A game of Snakes and Ladders with 25 squares:
// ○ ○ ▲ ○ ○ ▲ ○ ○ ▲ ▲ ○ ○ ○ ▼ ○ ○ ○ ○ ▼ ○ ○ ▼ ○ ▼ ○    
// Protocol Composition

protocol Named {
    var name: String { get }
}
protocol Aged {
    var age: Int { get }
}
struct Person: Named, Aged {
    var name: String
    var age: Int
}
// any type that conforms to both the Named and Aged protocols 
func wishHappyBirthday(celebrator: protocol<Named, Aged>) { 
    println("Happy birthday \(celebrator.name) - you're \(celebrator.age)!")
}
let birthdayPerson = Person(name: "Malcolm", age: 21)
wishHappyBirthday(birthdayPerson)
// prints "Happy birthday Malcolm - you're 21!" 

You can check for protocol conformance only if your protocol is marked with the @objc attribute, as seen for the HasArea protocol above. This attribute indicates that the protocol should be exposed to Objective-C code and is described in Using Swift with Cocoa and Objective-C. Even if you are not interoperating with Objective-C, you need to mark your protocols with the @objc attribute if you want to be able to check for protocol conformance.

Note also that @objc protocols can be adopted only by classes, and not by structures or enumerations. If you mark your protocol as @objc in order to check for conformance, you will be able to apply that protocol only to class types.

@objc protocol HasArea {
    var area: Double { get }
}

class Circle: HasArea {
    let pi = 3.1415927
    var radius: Double
    var area: Double { return pi * radius * radius }
    init(radius: Double) { self.radius = radius }
}
class Country: HasArea {
    var area: Double
    init(area: Double) { self.area = area }
}
class Animal {
    var legs: Int
    init(legs: Int) { self.legs = legs }
}   

let objects: AnyObject[] = [
    Circle(radius: 2.0),
    Country(area: 243_610),
    Animal(legs: 4)
]

for object in objects {
    if let objectWithArea = object as? HasArea {
        println("Area is \(objectWithArea.area)")
    } else {
        println("Something that doesn't have an area")
    }
}
// Area is 12.5663708
// Area is 243610.0
// Something that doesn't have an area  
// Optional Protocol Requirements 

@objc protocol CounterDataSource {
    @optional func incrementForCount(count: Int) -> Int
    @optional var fixedIncrement: Int { get }
}

@objc class Counter {
    var count = 0
    var dataSource: CounterDataSource?
    func increment() {
        if let amount = dataSource?.incrementForCount?(count) {
            count += amount
        } else if let amount = dataSource?.fixedIncrement? {
            count += amount
        }
    }
}

class ThreeSource: CounterDataSource {
    let fixedIncrement = 3
}

var counter = Counter()
counter.dataSource = ThreeSource()
for _ in 1...4 {
    counter.increment()
    println(counter.count)
}
// 3
// 6
// 9
// 12

class TowardsZeroSource: CounterDataSource {
    func incrementForCount(count: Int) -> Int {
        if count == 0 {
            return 0
        } else if count < 0 {
            return 1
        } else {
            return -1
        }
    }
}

counter.count = -4
counter.dataSource = TowardsZeroSource()
for _ in 1...5 {
    counter.increment()
    println(counter.count)
}
// -3
// -2
// -1
// 0
// 0      

Generics

func swapTwoValues<T>(inout a: T, inout b: T) {
    let temporaryA = a
    a = b
    b = temporaryA
}

var someInt = 3
var anotherInt = 107
swapTwoValues(&someInt, &anotherInt)
// someInt is now 107, and anotherInt is now 3

var someString = "hello"
var anotherString = "world"
swapTwoValues(&someString, &anotherString)
// someString is now "world", and anotherString is now "hello"  
struct Stack<T> {
    var items = T[]()
    mutating func push(item: T) {
        items.append(item)
    }
    mutating func pop() -> T {
        return items.removeLast()
    }
}

var stackOfStrings = Stack<String>()
stackOfStrings.push("uno")
stackOfStrings.push("dos")
stackOfStrings.push("tres")
stackOfStrings.push("cuatro")
// the stack now contains 4 strings
let fromTheTop = stackOfStrings.pop()
// fromTheTop is equal to "cuatro", and the stack now contains 3 strings   

Type Constraints:

func someFunction<T: SomeClass, U: SomeProtocol>(someT: T, someU: U) {
    // function body goes here
} 
func findIndex<T: Equatable>(array: T[], valueToFind: T) -> Int? {
    for (index, value) in enumerate(array) {
        if value == valueToFind {
            return index
        }
    }
    return nil
}

let doubleIndex = findIndex([3.14159, 0.1, 0.25], 9.3)
// doubleIndex is an optional Int with no value, because 9.3 is not in the array
let stringIndex = findIndex(["Mike", "Malcolm", "Andrea"], "Andrea")
// stringIndex is an optional Int containing a value of 2  

Associated Types:

protocol Container {
    typealias ItemType
    mutating func append(item: ItemType)
    var count: Int { get }
    subscript(i: Int) -> ItemType { get }
}

struct Stack<T>: Container {
    // original Stack<T> implementation
    var items = T[]()
    mutating func push(item: T) {
        items.append(item)
    }
    mutating func pop() -> T {
        return items.removeLast()
    }
    // conformance to the Container protocol
    // 自动推断出 typealias ItemType = T
    mutating func append(item: T) {
        self.push(item)
    }
    var count: Int {
    return items.count
    }
    subscript(i: Int) -> T {
        return items[i]
    }
}  
extension Array: Container {}

Array’s existing append method and subscript enable Swift to infer the appropriate type to use for ItemType, just as for the generic Stack type above. After defining this extension, you can use any Array as a Container.

Where Clauses:

func allItemsMatch<
    C1: Container, C2: Container
    where C1.ItemType == C2.ItemType, C1.ItemType: Equatable>
    (someContainer: C1, anotherContainer: C2) -> Bool {

        // check that both containers contain the same number of items
        if someContainer.count != anotherContainer.count {
            return false
        }

        // check each pair of items to see if they are equivalent
        for i in 0..someContainer.count {
            if someContainer[i] != anotherContainer[i] {
                return false
            }
        }

        // all items match, so return true
        return true

}

var stackOfStrings = Stack<String>()
stackOfStrings.push("uno")
stackOfStrings.push("dos")
stackOfStrings.push("tres")

var arrayOfStrings = ["uno", "dos", "tres"]

if allItemsMatch(stackOfStrings, arrayOfStrings) {
    println("All items match.")
} else {
    println("Not all items match.")
}
// prints "All items match."  

Advanced Operators

let initialBits: UInt8 = 0b00001111
let invertedBits = ~initialBits  // equals 11110000 

let firstSixBits: UInt8 = 0b11111100
let lastSixBits: UInt8  = 0b00111111
let middleFourBits = firstSixBits & lastSixBits  // equals 00111100

let someBits: UInt8 = 0b10110010
let moreBits: UInt8 = 0b01011110
let combinedbits = someBits | moreBits  // equals 11111110

let firstBits: UInt8 = 0b00010100
let otherBits: UInt8 = 0b00000101
let outputBits = firstBits ^ otherBits  // equals 00010001

let shiftBits: UInt8 = 4   // 00000100 in binary
shiftBits << 1             // 00001000
shiftBits << 2             // 00010000
shiftBits << 5             // 10000000
shiftBits << 6             // 00000000
shiftBits >> 2             // 00000001

let pink: UInt32 = 0xCC6699
let redComponent = (pink & 0xFF0000) >> 16    // redComponent is 0xCC, or 204
let greenComponent = (pink & 0x00FF00) >> 8   // greenComponent is 0x66, or 102
let blueComponent = pink & 0x0000FF           // blueComponent is 0x99, or 153    

// 如果允许溢出,在运算符前加&
var willOverflow = UInt8.max
// willOverflow equals 255, which is the largest value a UInt8 can hold
willOverflow = willOverflow &+ 1
// willOverflow is now equal to 0 

var willUnderflow = UInt8.min
// willUnderflow equals 0, which is the smallest value a UInt8 can hold
willUnderflow = willUnderflow &- 1
// willUnderflow is now equal to 255

var signedUnderflow = Int8.min
// signedUnderflow equals -128, which is the smallest value an Int8 can hold
signedUnderflow = signedUnderflow &- 1
// signedUnderflow is now equal to 127  

运算符重载:

struct Vector2D {
    var x = 0.0, y = 0.0
}
// It is said to be infix because it appears in between those two targets.
@infix func + (left: Vector2D, right: Vector2D) -> Vector2D {
    return Vector2D(x: left.x + right.x, y: left.y + right.y)
} 

let vector = Vector2D(x: 3.0, y: 1.0)
let anotherVector = Vector2D(x: 2.0, y: 4.0)
let combinedVector = vector + anotherVector
// combinedVector is a Vector2D instance with values of (5.0, 5.0)

@prefix func - (vector: Vector2D) -> Vector2D {
    return Vector2D(x: -vector.x, y: -vector.y)
}  

let positive = Vector2D(x: 3.0, y: 4.0)
let negative = -positive
// negative is a Vector2D instance with values of (-3.0, -4.0)
let alsoPositive = -negative
// alsoPositive is a Vector2D instance with values of (3.0, 4.0) 

// 复合赋值运算符
@assignment func += (inout left: Vector2D, right: Vector2D) {
    left = left + right
}

var original = Vector2D(x: 1.0, y: 2.0)
let vectorToAdd = Vector2D(x: 3.0, y: 4.0)
original += vectorToAdd
// original now has values of (4.0, 6.0)

@prefix @assignment func ++ (inout vector: Vector2D) -> Vector2D {
    vector += Vector2D(x: 1.0, y: 1.0)
    return vector
}

var toIncrement = Vector2D(x: 3.0, y: 4.0)
let afterIncrement = ++toIncrement
// toIncrement now has values of (4.0, 5.0)
// afterIncrement also has values of (4.0, 5.0)    

It is not possible to overload the default assignment operator (=). Only the compound assignment operators can be overloaded. Similarly, the ternary conditional operator (a ? b : c) cannot be overloaded.

// Equivalence Operators
@infix func == (left: Vector2D, right: Vector2D) -> Bool {
    return (left.x == right.x) && (left.y == right.y)
}
@infix func != (left: Vector2D, right: Vector2D) -> Bool {
    return !(left == right)
} 

let twoThree = Vector2D(x: 2.0, y: 3.0)
let anotherTwoThree = Vector2D(x: 2.0, y: 3.0)
if twoThree == anotherTwoThree {
    println("These two vectors are equivalent.")
}
// prints "These two vectors are equivalent." 

Custom operators can be defined only with the characters / = – + * % < > ! & | ^ . ~.

New operators are declared at a global level using the operator keyword, and can be declared as prefix, infix or postfix:

operator prefix +++ {}

@prefix @assignment func +++ (inout vector: Vector2D) -> Vector2D {
    vector += vector
    return vector
}

var toBeDoubled = Vector2D(x: 1.0, y: 4.0)
let afterDoubling = +++toBeDoubled
// toBeDoubled now has values of (2.0, 8.0)
// afterDoubling also has values of (2.0, 8.0)

Precedence and Associativity for Custom Infix Operators

operator infix +- { associativity left precedence 140 }
func +- (left: Vector2D, right: Vector2D) -> Vector2D {
    return Vector2D(x: left.x + right.x, y: left.y - right.y)
}
let firstVector = Vector2D(x: 1.0, y: 2.0)
let secondVector = Vector2D(x: 3.0, y: 4.0)
let plusMinusVector = firstVector +- secondVector
// plusMinusVector is a Vector2D instance with values of (4.0, -2.0)

A Swift Tour

Functions are actually a special case of closures. (In Swift, functions are just named closures) You can write a closure without a name by surrounding code with braces ({}). Use in to separate the arguments and return type from the body.

Methods on classes have one important difference from functions. Parameter names in functions are used only within the function, but parameters names in methods are also used when you call the method (except for the first parameter). By default, a method has the same name for its parameters when you call it and within the method itself. You can specify a second name, which is used inside the method.

// 错误
let convertedRank = Rank.fromRaw(3)  // convertedRank 的类型是Rank?
let threeDescription = convertedRank.toRaw() // optional type不能直接方法

//正确
let convertedRank = Rank.fromRaw(3)!
let threeDescription = convertedRank.toRaw()  // 3

// 正确
let convertedRank = Rank.fromRaw(3)
let threeDescription = convertedRank!.toRaw()  // 3

// 正确
let convertedRank = Rank.fromRaw(3)
let threeDescription = convertedRank?.toRaw()  // {some 3}

One of the most important differences between structures and classes is that structures are always copied when they are passed around in your code, but classes are passed by reference

结构体中的方法要修改结构体,需要加mutating关键字;类则不用,加了反而错误。

Use extension to add functionality to an existing type, such as new methods and computed properties. You can use an extension to add protocol conformance to a type that is declared elsewhere, or even to a type that you imported from a library or framework.

extension Int: ExampleProtocol {
    var simpleDescription: String {
    return "The number \(self)"
    }
    mutating func adjust() {
        self += 42
    }
}
7.simpleDescription 

You can use a protocol name just like any other named type—for example, to create a collection of objects that have different types but that all conform to a single protocol. When you work with values whose type is a protocol type, methods outside the protocol definition are not available.

let protocolValue: ExampleProtocol = a // a is an instance of SimpleClass, and SimpleClass adopt ExampleProtocol
protocolValue.simpleDescription
// protocolValue.anotherProperty  // Uncomment to see the error

Even though the variable protocolValue has a runtime type of SimpleClass, the compiler treats it as the given type of ExampleProtocol. This means that you can’t accidentally access methods or properties that the class implements in addition to its protocol conformance.

Google Java编程风格指南

Standard

原文:http://www.hawstein.com/posts/google-java-style.html

作者:Hawstein
出处:http://hawstein.com/posts/google-java-style.html
声明:本文采用以下协议进行授权: 自由转载-非商用-非衍生-保持署名|Creative Commons BY-NC-ND 3.0 ,转载请注明作者及出处。

目录

  1. 前言
  2. 源文件基础
  3. 源文件结构
  4. 格式
  5. 命名约定
  6. 编程实践
  7. Javadoc
  8. 后记

前言

这份文档是Google Java编程风格规范的完整定义。当且仅当一个Java源文件符合此文档中的规则, 我们才认为它符合Google的Java编程风格。

与其它的编程风格指南一样,这里所讨论的不仅仅是编码格式美不美观的问题, 同时也讨论一些约定及编码标准。然而,这份文档主要侧重于我们所普遍遵循的规则, 对于那些不是明确强制要求的,我们尽量避免提供意见。

1.1 术语说明

在本文档中,除非另有说明:

  1. 术语class可表示一个普通类,枚举类,接口或是annotation类型(@interface)
  2. 术语comment只用来指代实现的注释(implementation comments),我们不使用“documentation comments”一词,而是用Javadoc。

其他的术语说明会偶尔在后面的文档出现。

1.2 指南说明

本文档中的示例代码并不作为规范。也就是说,虽然示例代码是遵循Google编程风格,但并不意味着这是展现这些代码的唯一方式。 示例中的格式选择不应该被强制定为规则。

源文件基础

2.1 文件名

源文件以其最顶层的类名来命名,大小写敏感,文件扩展名为.java

2.2 文件编码:UTF-8

源文件编码格式为UTF-8。

2.3 特殊字符

2.3.1 空白字符

除了行结束符序列,ASCII水平空格字符(0x20,即空格)是源文件中唯一允许出现的空白字符,这意味着:

  1. 所有其它字符串中的空白字符都要进行转义。
  2. 制表符不用于缩进。

2.3.2 特殊转义序列

对于具有特殊转义序列的任何字符(\b, \t, \n, \f, \r, \“, \‘及\),我们使用它的转义序列,而不是相应的八进制(比如\012)或Unicode(比如\u000a)转义。

2.3.3 非ASCII字符

对于剩余的非ASCII字符,是使用实际的Unicode字符(比如∞),还是使用等价的Unicode转义符(比如\u221e),取决于哪个能让代码更易于阅读和理解。

Tip: 在使用Unicode转义符或是一些实际的Unicode字符时,建议做些注释给出解释,这有助于别人阅读和理解。

例如:

String unitAbbrev = "μs";                                 | 赞,即使没有注释也非常清晰
String unitAbbrev = "\u03bcs"; // "μs"                    | 允许,但没有理由要这样做
String unitAbbrev = "\u03bcs"; // Greek letter mu, "s"    | 允许,但这样做显得笨拙还容易出错
String unitAbbrev = "\u03bcs";                            | 很糟,读者根本看不出这是什么
return '\ufeff' + content; // byte order mark             | Good,对于非打印字符,使用转义,并在必要时写上注释

Tip: 永远不要由于害怕某些程序可能无法正确处理非ASCII字符而让你的代码可读性变差。当程序无法正确处理非ASCII字符时,它自然无法正确运行, 你就会去fix这些问题的了。(言下之意就是大胆去用非ASCII字符,如果真的有需要的话)

源文件结构

一个源文件包含(按顺序地):

  1. 许可证或版权信息(如有需要)
  2. package语句
  3. import语句
  4. 一个顶级类(只有一个)

以上每个部分之间用一个空行隔开。

3.1 许可证或版权信息

如果一个文件包含许可证或版权信息,那么它应当被放在文件最前面。

3.2 package语句

package语句不换行,列限制(4.4节)并不适用于package语句。(即package语句写在一行里)

3.3 import语句

3.3.1 import不要使用通配符

即,不要出现类似这样的import语句:import java.util.*;

3.3.2 不要换行

import语句不换行,列限制(4.4节)并不适用于import语句。(每个import语句独立成行)

3.3.3 顺序和间距

import语句可分为以下几组,按照这个顺序,每组由一个空行分隔:

  1. 所有的静态导入独立成组
  2. com.google imports(仅当这个源文件是在com.google包下)
  3. 第三方的包。每个顶级包为一组,字典序。例如:android, com, junit, org, sun
  4. java imports
  5. javax imports

组内不空行,按字典序排列。

3.4 类声明

3.4.1 只有一个顶级类声明

每个顶级类都在一个与它同名的源文件中(当然,还包含.java后缀)。

例外:package-info.java,该文件中可没有package-info类。

3.4.2 类成员顺序

类的成员顺序对易学性有很大的影响,但这也不存在唯一的通用法则。不同的类对成员的排序可能是不同的。 最重要的一点,每个类应该以某种逻辑去排序它的成员,维护者应该要能解释这种排序逻辑。比如, 新的方法不能总是习惯性地添加到类的结尾,因为这样就是按时间顺序而非某种逻辑来排序的。

3.4.2.1 重载:永不分离

当一个类有多个构造函数,或是多个同名方法,这些函数/方法应该按顺序出现在一起,中间不要放进其它函数/方法。

格式

术语说明:块状结构(block-like construct)指的是一个类,方法或构造函数的主体。需要注意的是,数组初始化中的初始值可被选择性地视为块状结构(4.8.3.1节)。

4.1 大括号

4.1.1 使用大括号(即使是可选的)

大括号与if, else, for, do, while语句一起使用,即使只有一条语句(或是空),也应该把大括号写上。

4.1.2 非空块:K & R 风格

对于非空块和块状结构,大括号遵循Kernighan和Ritchie风格 (Egyptian brackets):

  • 左大括号前不换行
  • 左大括号后换行
  • 右大括号前换行
  • 如果右大括号是一个语句、函数体或类的终止,则右大括号后换行; 否则不换行。例如,如果右大括号后面是else或逗号,则不换行。

示例:

return new MyClass() {
  @Override public void method() {
    if (condition()) {
      try {
        something();
      } catch (ProblemException e) {
        recover();
      }
    }
  }
};

4.8.1节给出了enum类的一些例外。

4.1.3 空块:可以用简洁版本

一个空的块状结构里什么也不包含,大括号可以简洁地写成{},不需要换行。例外:如果它是一个多块语句的一部分(if/else 或 try/catch/finally) ,即使大括号内没内容,右大括号也要换行。

示例:

void doNothing() {}

4.2 块缩进:2个空格

每当开始一个新的块,缩进增加2个空格,当块结束时,缩进返回先前的缩进级别。缩进级别适用于代码和注释。(见4.1.2节中的代码示例)

4.3 一行一个语句

每个语句后要换行。

4.4 列限制:80或100

一个项目可以选择一行80个字符或100个字符的列限制,除了下述例外,任何一行如果超过这个字符数限制,必须自动换行。

例外:

  1. 不可能满足列限制的行(例如,Javadoc中的一个长URL,或是一个长的JSNI方法参考)。
  2. packageimport语句(见3.2节和3.3节)。
  3. 注释中那些可能被剪切并粘贴到shell中的命令行。

4.5 自动换行

术语说明:一般情况下,一行长代码为了避免超出列限制(80或100个字符)而被分为多行,我们称之为自动换行(line-wrapping)。

我们并没有全面,确定性的准则来决定在每一种情况下如何自动换行。很多时候,对于同一段代码会有好几种有效的自动换行方式。

Tip: 提取方法或局部变量可以在不换行的情况下解决代码过长的问题(是合理缩短命名长度吧)

4.5.1 从哪里断开

自动换行的基本准则是:更倾向于在更高的语法级别处断开。

  1. 如果在非赋值运算符处断开,那么在该符号前断开(比如+,它将位于下一行)。注意:这一点与Google其它语言的编程风格不同(如C++和JavaScript)。 这条规则也适用于以下“类运算符”符号:点分隔符(.),类型界限中的&(<T extends Foo & Bar>),catch块中的管道符号(catch (FooException | BarException e)
  2. 如果在赋值运算符处断开,通常的做法是在该符号后断开(比如=,它与前面的内容留在同一行)。这条规则也适用于foreach语句中的分号。
  3. 方法名或构造函数名与左括号留在同一行。
  4. 逗号(,)与其前面的内容留在同一行。

4.5.2 自动换行时缩进至少+4个空格

自动换行时,第一行后的每一行至少比第一行多缩进4个空格(注意:制表符不用于缩进。见2.3.1节)。

当存在连续自动换行时,缩进可能会多缩进不只4个空格(语法元素存在多级时)。一般而言,两个连续行使用相同的缩进当且仅当它们开始于同级语法元素。

第4.6.3水平对齐一节中指出,不鼓励使用可变数目的空格来对齐前面行的符号。

4.6 空白

4.6.1 垂直空白

以下情况需要使用一个空行:

  1. 类内连续的成员之间:字段,构造函数,方法,嵌套类,静态初始化块,实例初始化块。
    • 例外:两个连续字段之间的空行是可选的,用于字段的空行主要用来对字段进行逻辑分组。
  2. 在函数体内,语句的逻辑分组间使用空行。
  3. 类内的第一个成员前或最后一个成员后的空行是可选的(既不鼓励也不反对这样做,视个人喜好而定)。
  4. 要满足本文档中其他节的空行要求(比如3.3节:import语句)

多个连续的空行是允许的,但没有必要这样做(我们也不鼓励这样做)。

4.6.2 水平空白

除了语言需求和其它规则,并且除了文字,注释和Javadoc用到单个空格,单个ASCII空格也出现在以下几个地方:

  1. 分隔任何保留字与紧随其后的左括号(()(如if, for catch等)。
  2. 分隔任何保留字与其前面的右大括号(})(如else, catch)。
  3. 在任何左大括号前({),两个例外:
    • @SomeAnnotation({a, b})(不使用空格)。
    • String[][] x = foo;(大括号间没有空格,见下面的Note)。
  4. 在任何二元或三元运算符的两侧。这也适用于以下“类运算符”符号:
    • 类型界限中的&(<T extends Foo & Bar>)。
    • catch块中的管道符号(catch (FooException | BarException e)。
    • foreach语句中的分号。
  5. , : ;及右括号())后
  6. 如果在一条语句后做注释,则双斜杠(//)两边都要空格。这里可以允许多个空格,但没有必要。
  7. 类型和变量之间:List list。
  8. 数组初始化中,大括号内的空格是可选的,即new int[] {5, 6}new int[] { 5, 6 }都是可以的。

Note:这个规则并不要求或禁止一行的开关或结尾需要额外的空格,只对内部空格做要求。

4.6.3 水平对齐:不做要求

术语说明:水平对齐指的是通过增加可变数量的空格来使某一行的字符与上一行的相应字符对齐。

这是允许的(而且在不少地方可以看到这样的代码),但Google编程风格对此不做要求。即使对于已经使用水平对齐的代码,我们也不需要去保持这种风格。

以下示例先展示未对齐的代码,然后是对齐的代码:

private int x; // this is fine
private Color color; // this too

private int   x;      // permitted, but future edits
private Color color;  // may leave it unaligned

Tip:对齐可增加代码可读性,但它为日后的维护带来问题。考虑未来某个时候,我们需要修改一堆对齐的代码中的一行。 这可能导致原本很漂亮的对齐代码变得错位。很可能它会提示你调整周围代码的空白来使这一堆代码重新水平对齐(比如程序员想保持这种水平对齐的风格), 这就会让你做许多的无用功,增加了reviewer的工作并且可能导致更多的合并冲突。

4.7 用小括号来限定组:推荐

除非作者和reviewer都认为去掉小括号也不会使代码被误解,或是去掉小括号能让代码更易于阅读,否则我们不应该去掉小括号。 我们没有理由假设读者能记住整个Java运算符优先级表。

4.8 具体结构

4.8.1 枚举类

枚举常量间用逗号隔开,换行可选。

没有方法和文档的枚举类可写成数组初始化的格式:

private enum Suit { CLUBS, HEARTS, SPADES, DIAMONDS }

由于枚举类也是一个类,因此所有适用于其它类的格式规则也适用于枚举类。

4.8.2 变量声明

4.8.2.1 每次只声明一个变量

不要使用组合声明,比如int a, b;

4.8.2.2 需要时才声明,并尽快进行初始化

不要在一个代码块的开头把局部变量一次性都声明了(这是c语言的做法),而是在第一次需要使用它时才声明。 局部变量在声明时最好就进行初始化,或者声明后尽快进行初始化。

4.8.3 数组

4.8.3.1 数组初始化:可写成块状结构

数组初始化可以写成块状结构,比如,下面的写法都是OK的:

new int[] {
  0, 1, 2, 3 
}

new int[] {
  0,
  1,
  2,
  3
}

new int[] {
  0, 1,
  2, 3
}

new int[]
    {0, 1, 2, 3}
4.8.3.2 非C风格的数组声明

中括号是类型的一部分:String[] args, 而非String args[]

4.8.4 switch语句

术语说明:switch块的大括号内是一个或多个语句组。每个语句组包含一个或多个switch标签(case FOO:default:),后面跟着一条或多条语句。

4.8.4.1 缩进

与其它块状结构一致,switch块中的内容缩进为2个空格。

每个switch标签后新起一行,再缩进2个空格,写下一条或多条语句。

4.8.4.2 Fall-through:注释

在一个switch块内,每个语句组要么通过break, continue, return或抛出异常来终止,要么通过一条注释来说明程序将继续执行到下一个语句组, 任何能表达这个意思的注释都是OK的(典型的是用// fall through)。这个特殊的注释并不需要在最后一个语句组(一般是default)中出现。示例:

switch (input) {
  case 1:
  case 2:
    prepareOneOrTwo();
    // fall through
  case 3:
    handleOneTwoOrThree();
    break;
  default:
    handleLargeNumber(input);
}
4.8.4.3 default的情况要写出来

每个switch语句都包含一个default语句组,即使它什么代码也不包含。

4.8.5 注解(Annotations)

注解紧跟在文档块后面,应用于类、方法和构造函数,一个注解独占一行。这些换行不属于自动换行(第4.5节,自动换行),因此缩进级别不变。例如:

@Override
@Nullable
public String getNameIfPresent() { ... }

例外:单个的注解可以和签名的第一行出现在同一行。例如:

@Override public int hashCode() { ... }

应用于字段的注解紧随文档块出现,应用于字段的多个注解允许与字段出现在同一行。例如:

@Partial @Mock DataLoader loader;

参数和局部变量注解没有特定规则。

4.8.6 注释

4.8.6.1 块注释风格

块注释与其周围的代码在同一缩进级别。它们可以是/* ... */风格,也可以是// ...风格。对于多行的/* ... */注释,后续行必须从*开始, 并且与前一行的*对齐。以下示例注释都是OK的。

/*
 * This is          // And so           /* Or you can
 * okay.            // is this.          * even do this. */
 */

注释不要封闭在由星号或其它字符绘制的框架里。

Tip:在写多行注释时,如果你希望在必要时能重新换行(即注释像段落风格一样),那么使用/* ... */

4.8.7 Modifiers

类和成员的modifiers如果存在,则按Java语言规范中推荐的顺序出现。

public protected private abstract static final transient volatile synchronized native strictfp

命名约定

5.1 对所有标识符都通用的规则

标识符只能使用ASCII字母和数字,因此每个有效的标识符名称都能匹配正则表达式\w+

在Google其它编程语言风格中使用的特殊前缀或后缀,如name_mNames_namekName,在Java编程风格中都不再使用。

5.2 标识符类型的规则

5.2.1 包名

包名全部小写,连续的单词只是简单地连接起来,不使用下划线。

5.2.2 类名

类名都以UpperCamelCase风格编写。

类名通常是名词或名词短语,接口名称有时可能是形容词或形容词短语。现在还没有特定的规则或行之有效的约定来命名注解类型。

测试类的命名以它要测试的类的名称开始,以Test结束。例如,HashTestHashIntegrationTest

5.2.3 方法名

方法名都以lowerCamelCase风格编写。

方法名通常是动词或动词短语。

下划线可能出现在JUnit测试方法名称中用以分隔名称的逻辑组件。一个典型的模式是:test<MethodUnderTest>_<state>,例如testPop_emptyStack。 并不存在唯一正确的方式来命名测试方法。

5.2.4 常量名

常量名命名模式为CONSTANT_CASE,全部字母大写,用下划线分隔单词。那,到底什么算是一个常量?

每个常量都是一个静态final字段,但不是所有静态final字段都是常量。在决定一个字段是否是一个常量时, 考虑它是否真的感觉像是一个常量。例如,如果任何一个该实例的观测状态是可变的,则它几乎肯定不会是一个常量。 只是永远不打算改变对象一般是不够的,它要真的一直不变才能将它示为常量。

// Constants
static final int NUMBER = 5;
static final ImmutableList<String> NAMES = ImmutableList.of("Ed", "Ann");
static final Joiner COMMA_JOINER = Joiner.on(',');  // because Joiner is immutable
static final SomeMutableType[] EMPTY_ARRAY = {};
enum SomeEnum { ENUM_CONSTANT }

// Not constants
static String nonFinal = "non-final";
final String nonStatic = "non-static";
static final Set<String> mutableCollection = new HashSet<String>();
static final ImmutableSet<SomeMutableType> mutableElements = ImmutableSet.of(mutable);
static final Logger logger = Logger.getLogger(MyClass.getName());
static final String[] nonEmptyArray = {"these", "can", "change"};

这些名字通常是名词或名词短语。

5.2.5 非常量字段名

非常量字段名以lowerCamelCase风格编写。

这些名字通常是名词或名词短语。

5.2.6 参数名

参数名以lowerCamelCase风格编写。

参数应该避免用单个字符命名。

5.2.7 局部变量名

局部变量名以lowerCamelCase风格编写,比起其它类型的名称,局部变量名可以有更为宽松的缩写。

虽然缩写更宽松,但还是要避免用单字符进行命名,除了临时变量和循环变量。

即使局部变量是final和不可改变的,也不应该把它示为常量,自然也不能用常量的规则去命名它。

5.2.8 类型变量名

类型变量可用以下两种风格之一进行命名:

  • 单个的大写字母,后面可以跟一个数字(如:E, T, X, T2)。
  • 以类命名方式(5.2.2节),后面加个大写的T(如:RequestT, FooBarT)。

5.3 驼峰式命名法(CamelCase)

驼峰式命名法分大驼峰式命名法(UpperCamelCase)和小驼峰式命名法(lowerCamelCase)。 有时,我们有不只一种合理的方式将一个英语词组转换成驼峰形式,如缩略语或不寻常的结构(例如”IPv6″或”iOS”)。Google指定了以下的转换方案。

名字从散文形式(prose form)开始:

  1. 把短语转换为纯ASCII码,并且移除任何单引号。例如:”Müller’s algorithm”将变成”Muellers algorithm”。
  2. 把这个结果切分成单词,在空格或其它标点符号(通常是连字符)处分割开。
    • 推荐:如果某个单词已经有了常用的驼峰表示形式,按它的组成将它分割开(如”AdWords”将分割成”ad words”)。 需要注意的是”iOS”并不是一个真正的驼峰表示形式,因此该推荐对它并不适用。
  3. 现在将所有字母都小写(包括缩写),然后将单词的第一个字母大写:
    • 每个单词的第一个字母都大写,来得到大驼峰式命名。
    • 除了第一个单词,每个单词的第一个字母都大写,来得到小驼峰式命名。
  4. 最后将所有的单词连接起来得到一个标识符。

示例:

Prose form                Correct               Incorrect
------------------------------------------------------------------
"XML HTTP request"        XmlHttpRequest        XMLHTTPRequest
"new customer ID"         newCustomerId         newCustomerID
"inner stopwatch"         innerStopwatch        innerStopWatch
"supports IPv6 on iOS?"   supportsIpv6OnIos     supportsIPv6OnIOS
"YouTube importer"        YouTubeImporter
                          YoutubeImporter*

加星号处表示可以,但不推荐。

Note:在英语中,某些带有连字符的单词形式不唯一。例如:”nonempty”和”non-empty”都是正确的,因此方法名checkNonemptycheckNonEmpty也都是正确的。

编程实践

6.1 @Override:能用则用

只要是合法的,就把@Override注解给用上。

6.2 捕获的异常:不能忽视

除了下面的例子,对捕获的异常不做响应是极少正确的。(典型的响应方式是打印日志,或者如果它被认为是不可能的,则把它当作一个AssertionError重新抛出。)

如果它确实是不需要在catch块中做任何响应,需要做注释加以说明(如下面的例子)。

try {
  int i = Integer.parseInt(response);
  return handleNumericResponse(i);
} catch (NumberFormatException ok) {
  // it's not numeric; that's fine, just continue
}
return handleTextResponse(response);

例外:在测试中,如果一个捕获的异常被命名为expected,则它可以被不加注释地忽略。下面是一种非常常见的情形,用以确保所测试的方法会抛出一个期望中的异常, 因此在这里就没有必要加注释。

try {
  emptyStack.pop();
  fail();
} catch (NoSuchElementException expected) {
}

6.3 静态成员:使用类进行调用

使用类名调用静态的类成员,而不是具体某个对象或表达式。

Foo aFoo = ...;
Foo.aStaticMethod(); // good
aFoo.aStaticMethod(); // bad
somethingThatYieldsAFoo().aStaticMethod(); // very bad

6.4 Finalizers: 禁用

极少会去重载Object.finalize

Tip:不要使用finalize。如果你非要使用它,请先仔细阅读和理解Effective Java 第7条款:“Avoid Finalizers”,然后不要使用它。

Javadoc

7.1 格式

7.1.1 一般形式

Javadoc块的基本格式如下所示:

/**
 * Multiple lines of Javadoc text are written here,
 * wrapped normally...
 */
public int method(String p1) { ... }

或者是以下单行形式:

/** An especially short bit of Javadoc. */

基本格式总是OK的。当整个Javadoc块能容纳于一行时(且没有Javadoc标记@XXX),可以使用单行形式。

7.1.2 段落

空行(即,只包含最左侧星号的行)会出现在段落之间和Javadoc标记(@XXX)之前(如果有的话)。 除了第一个段落,每个段落第一个单词前都有标签<p>,并且它和第一个单词间没有空格。

7.1.3 Javadoc标记

标准的Javadoc标记按以下顺序出现:@param@return@throws@deprecated, 前面这4种标记如果出现,描述都不能为空。 当描述无法在一行中容纳,连续行需要至少再缩进4个空格。

7.2 摘要片段

每个类或成员的Javadoc以一个简短的摘要片段开始。这个片段是非常重要的,在某些情况下,它是唯一出现的文本,比如在类和方法索引中。

这只是一个小片段,可以是一个名词短语或动词短语,但不是一个完整的句子。它不会以A {@code Foo} is a...This method returns...开头, 它也不会是一个完整的祈使句,如Save the record...。然而,由于开头大写及被加了标点,它看起来就像是个完整的句子。

Tip:一个常见的错误是把简单的Javadoc写成/** @return the customer ID */,这是不正确的。它应该写成/** Returns the customer ID. */

7.3 哪里需要使用Javadoc

至少在每个public类及它的每个public和protected成员处使用Javadoc,以下是一些例外:

7.3.1 例外:不言自明的方法

对于简单明显的方法如getFoo,Javadoc是可选的(即,是可以不写的)。这种情况下除了写“Returns the foo”,确实也没有什么值得写了。

单元测试类中的测试方法可能是不言自明的最常见例子了,我们通常可以从这些方法的描述性命名中知道它是干什么的,因此不需要额外的文档说明。

Tip:如果有一些相关信息是需要读者了解的,那么以上的例外不应作为忽视这些信息的理由。例如,对于方法名getCanonicalName, 就不应该忽视文档说明,因为读者很可能不知道词语canonical name指的是什么。

7.3.2 例外:重载

如果一个方法重载了超类中的方法,那么Javadoc并非必需的。

7.3.3 可选的Javadoc

对于包外不可见的类和方法,如有需要,也是要使用Javadoc的。如果一个注释是用来定义一个类,方法,字段的整体目的或行为, 那么这个注释应该写成Javadoc,这样更统一更友好。

后记

本文档翻译自Google Java Style, 译者@Hawstein

List Of 10 Funny Linux Commands

Standard

by Rajneesh Upadhyay

Working from the Terminal is really fun. Today, we’ll list really funny Linux commands which will bring smile on your face.

 1. rev

Create a file, type some words in this file, rev command will dump all words written by you in reverse.

# rev  <file name>

Selection_002

Selection_001

 2. fortune

This command is not install by default, install with apt-get and fortune will display some random sentence.

crank@crank-System:~$ sudo apt-get install fortune

Selection_003

Use -s option with fortune, it will limit the out to one sentence.

# fortune -s

Selection_004

3. yes

#yes <string>

This command will keep displaying the string for infinite time until the process is killed by the user.

# yes unixmen

Selection_005

4. figlet

This command can be installed with apt-get, comes with some ascii fonts which are located in /usr/share/figlet.

cd /usr/share/figlet
#figlet -f <font>  <string>

e.g.

#figlet -f big.flf unixmen

Selection_006

#figlet -f block.flf  unixmen
Selection_007

You can try another options also.

5. asciiquarium

This command will transform your terminal in to a Sea Aquarium.

Download term animator
# wget http://search.cpan.org/CPAN/authors/id/K/KB/KBAUCOM/Term-Animation-2.4.tar.gz

Install and Configure above package.

# tar -zxvf Term-Animation-2.4.tar.gz
# cd Term-Animation-2.4/
# perl Makefile.PL && make && make test
# sudo make install

Install following package:

# apt-get install libcurses-perl

Download and install asciiquarium

# wget http://www.robobunny.com/projects/asciiquarium/asciiquarium.tar.gz
# tar -zxvf asciiquarium.tar.gz 
# cd asciiquarium_1.0/
# cp asciiquarium /usr/local/bin/

Run,

# /usr/local/bin/asciiquarium

 asciiquarium_1.1 : perl_008

6. bb

# apt-get install bb
# bb

See what comes out:

Selection_009

 7. sl

Sometimes you type sl instead of ls by mistake,actually  sl is a command and a locomotive engine will start moving if you type sl.

# apt-get install sl
# sl

Selection_012

 8. cowsay

Very common command, is will display in ascii form whatever you wants to say.

apt-get install cowsay
# cowsay <string>

Selection_013

Or, you can use another character instead of com, such characters are stored in /usr/share/cowsay/cows

# cd /usr/share/cowsay/cows
cowsay -f ghostbusters.cow  unixmen

Selection_014or

# cowsay -f bud-frogs.cow Rajneesh
Selection_015

 9. toilet

Yes, this is a command, it dumps ascii strings in colored form to the terminal.

# apt-get install toilet
# toilet --gay unixmen
Selection_016
 toilet -F border -F gay unixmen

Selection_020

toilet  -f mono12 -F metal  unixmen

Selection_018

 10. aafire

Put you terminal on fire with aafire.

# apt-get install libaa-bin
# aafire

Selection_019

That it, Have fun with Linux Terminal!!

Sending Email Using Stored Procedures in Sql Server

Standard
原文:http://www.codeproject.com/Articles/1028172/Sending-Email-Using-Stored-Procedures-in-Sql-Serve

Introduction

A very interesting topic of discussion. We have mail integrated to every application now a days. We integrate email using SMTP settings in the Web.Config in .NET and use the Send method to send mails. Recently, I came across an interesting challenge, where we were to send emails from our SQL Server. Suppose we have to track the successful scheduled sql query execution. We cannot look into the tables it modified every time in order to check if it actually ran through successfully. It would be so nice, if we could get some kind of notification which can help us know about the status of execution. Yes, it is possible to send mails from our sql server using few stored procedures which are actually pre-defined.
Lets learn how:-done

Get Started

Remember we will be using pre defined Stored procedure to send the mails. First of all we need to set up an account with the credentials required by the server to send the mails. Usually the mail is sent through SMTP, Simple Mail Transfer Protocol. The settings would depend on the server your aplication demands. Remember the configuration needs to be valid.
Create a Database Account:-

EXEC msdb.dbo.sysmail_add_account_sp
    @account_name = 'SendEmailSqlDemoAccount'
  , @description = 'Sending SMTP mails to users'
  , @email_address = 'suraj.0241@gmail.com'
  , @display_name = 'Suraj Sahoo'
  , @replyto_address = 'suraj.0241@gmail.com'
  , @mailserver_name = 'smtp.gmail.com'
  , @port = 587
  , @username = 'XXXXXX'
  , @password = 'XXXXXX'
Go

Please use proper credentials and server settings in order to successfully deliver the mails, else they will fail and be queued.
Nextstep is to create a profile which would be used to tconfigure the database mail. The sp would look like below:

EXEC msdb.dbo.sysmail_add_profile_sp
    @profile_name = 'SendEmailSqlDemoProfile'
  , @description = 'Mail Profile description'
Go

This profile would be used in order to set the mail configuration and the emails and sent.
Next step is to map the account to the profile. This will let the profile know, which account credentials it need to work for sending successfully.
That would look like:

-- Add the account to the profile
EXEC msdb.dbo.sysmail_add_profileaccount_sp
    @profile_name = 'SendEmailSqlDemo'
  , @account_name = 'SendEmailSql'
  , @sequence_number = 1
GO

Thus, we are all set to send the successly emails. The mail sending look up snippet would look like below:

EXEC msdb.dbo.sp_send_dbmail
    @profile_name = 'SendEmailSqlDemo2'
  , @recipients = 'suraj.0241@gmail.com'
  , @subject = 'Automated Test Results (Successful)'
  , @body = 'The stored procedure finished successfully.'
  , @importance ='HIGH' 
GO

The stored procedured being used are sometimes vulnerable to not getting executed. So Try catch block and Begin and End Transaction are mandatory in few Stored Procedures.
Lets take an example here,
Suppose we have a SELECT INSERT query using Stored Procedure, so what happens is we are selecting and inserting from 4 tables, lets say
Users | UserLogin | UserEmployment | Departments
For each new screen creation we are manipulating and selecting the users based on their PK and inserting again into the same tables with a different FK, representing the particular screen. The query would look like below:-

BEGIN TRY
  BEGIN TRAN
 INSERT INTO
   dbo.[User]
 SELECT
    us.UserName,
	us.UserAddress,
	us.UserPhone,
    @fkScreenID
 FROM
   dbo.[User] as us
 WHERE
   UserID= @userID
 COMMIT TRAN
    END TRY
   BEGIN CATCH
  ROLLBACK TRAN
  END
  END CATCH  //Similarly for other tables as well we continue. Its is better to add the Try Catch to whole SP Executing Block

Here, when the transaction in case fails, it would move into the Catch block and there we can have the email sending procedure so as to get a notification regarding the success or failure and reason and where it failed. This would be so helpful for any developer.

Troubleshooting Mails

There are also stored procedure to let us know if the mails are successful, failed or remained in the queue. This is fascinating feature. Smile | :) .
To check for the mails which were successfully sent and delivered, we run the below query:

select * from msdb.dbo.sysmail_sentitems

Some of the columns it returns are
Email1
Email2
In the second image you can see we have the sent_status as sent, which states the mail has been successfully sent.

To check for the unsent mails which could not be sent, we run the below query:

select * from msdb.dbo.sysmail_unsentitems

TO check for the failed mails, which will not even be retried to be sent from the queue, we run the below query:-

select * from msdb.dbo.sysmail_faileditems

For more details on the failure along with the reason, the trouble shoot query would look like:

SELECT items.subject,
    items.last_mod_date
    ,l.description FROM msdb.dbo.sysmail_faileditems as items
INNER JOIN msdb.dbo.sysmail_event_log AS l
    ON items.mailitem_id = l.mailitem_id
GO

The results look like below:
Email3

The error description above is like “No Such Host” Error. This error usually comes when we have some smtp server connection settings wrong. We need to troubleshoot that on our own and recheck the settings credentials and then try. If then it does not seem to work, we need to look for the DNS server settings and retry with the configuration again. Nothing to worry for this though..Smile | :)

Conclusion

Thus we discussed here about sending mails from our own SQL using the stored procedures and how helpful they can prove to be. Troubleshooting the errors is very easy here and the set as well.
Exceptions and errors are a part of development which cannot be avoided but handling them is a challenge and developers can easily do that. :)

References

Email Architect
MSDN

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

为什么主引导记录的内存地址是0x7C00?

Standard

作者: 阮一峰

日期: 2015年9月28日

《计算机原理》课本说,启动时,主引导记录会存入内存地址0x7C00。

这个奇怪的地址,是怎么来的,课本就不解释了。我一直有疑问,为什么不存入内存的头部、尾部、或者其他位置,而偏偏存入这个比 32KB 小1024字节的地方?

昨天,我读到一篇文章,终于解开了这个谜。

首先,如果你不知道,主引导记录(Master boot record,缩写为MBR)是什么,可以先读《计算机是如何启动的?》

简单说,计算机启动是这样一个过程。

  1. 通电
  2. 读取ROM里面的BIOS,用来检查硬件
  3. 硬件检查通过
  4. BIOS根据指定的顺序,检查引导设备的第一个扇区(即主引导记录),加载在内存地址 0x7C00
  5. 主引导记录把操作权交给操作系统

所以,主引导记录就是引导”操作系统”进入内存的一段小程序,大小不超过1个扇区(512字节)。

0x7C00这个地址来自Intel的第一代个人电脑芯片8088,以后的CPU为了保持兼容,一直使用这个地址。

1981年8月,IBM公司最早的个人电脑IBM PC 5150上市,就用了这个芯片。

当时,搭配的操作系统是86-DOS。这个操作系统需要的内存最少是32KB。我们知道,内存地址从0x0000开始编号,32KB的内存就是0x0000~0x7FFF

8088芯片本身需要占用0x0000~0x03FF,用来保存各种中断处理程序的储存位置。(主引导记录本身就是中断信号INT 19h的处理程序。)所以,内存只剩下0x0400~0x7FFF可以使用。

为了把尽量多的连续内存留给操作系统,主引导记录就被放到了内存地址的尾部。由于一个扇区是512字节,主引导记录本身也会产生数据,需要另外留出512字节保存。所以,它的预留位置就变成了:


  0x7FFF - 512 - 512 + 1 = 0x7C00 

0x7C00就是这样来的。

计算机启动后,32KB内存的使用情况如下。


+--------------------- 0x0
| Interrupts vectors
+--------------------- 0x400
| BIOS data area
+--------------------- 0x5??
| OS load area
+--------------------- 0x7C00
| Boot sector
+--------------------- 0x7E00
| Boot data/stack
+--------------------- 0x7FFF
| (not used)
+--------------------- (...)

(完)

Node.js 4.0 中的 ES 6 特性介绍

Standard

原文:http://www.cli-nerd.com/2015/09/09/7-reasons-to-upgrade-to-node-v4-now.html作者: Damien Klinnert
译文:LCTT  https://linux.cn/article-6212-1.html译者: wxy

Node.js 4.0.0 已经发布了。这是和 io.js 合并之后的首个稳定版本,它带来了一系列的新特性,支持 ES 6的大部分特性。已经有很多 ES 6 的特性介绍了,这里我们介绍一下该怎么使用它们。

1. 模板字符串

如果你要在 JavaScript 中创建多行字符串,你可能会使用如下的语法:

  1. var message = [
  2. 'The quick brown fox',
  3. 'jumps over',
  4. 'the lazy dog'
  5. ].join('\n');

对于少量字符串这还算合适,但是如果比较多就会显得混乱。不过,有个聪明的开发者提出了一个叫 multiline 的技巧:

  1. var multiline = require('multiline');
  2. var message = multiline(function () {/*
  3. The quick brown fox
  4. jumps over
  5. the lazy dog
  6. */});

幸运的是,ES 6 为我们带来了模板字符串:

  1. var message = `
  2. The quick brown fox
  3. jumps over
  4. the lazy dog
  5. `;

此外,它还给我们带来了字符串内插:

  1. var name = 'Schroedinger';
  2. // 不要这样做 ...
  3. var message = 'Hello ' + name + ', how is your cat?';
  4. var message = ['Hello ', name, ', how is your cat?'].join('');
  5. var message = require('util').format('Hello %s, how is your cat?', name);
  6. // 应该这样做 ...
  7. var message = `Hello ${name}, how is your cat?`;

在 MDN 上查看模板字符串的细节.

2. 类

在 ES5 中定义类看起来有点奇怪,也比较麻烦:

  1. var Pet = function (name) {
  2. this._name = name;
  3. };
  4. Pet.prototype.sayHello = function () {
  5. console.log('*scratch*');
  6. };
  7. Object.defineProperty(Pet.prototype, 'name', {
  8. get: function () {
  9. return this._name;
  10. }
  11. });
  12. var Cat = function (name) {
  13. Pet.call(this, name);
  14. };
  15. require('util').inherits(Cat, Pet);
  16. Cat.prototype.sayHello = function () {
  17. Pet.prototype.sayHello.call(this);
  18. console.log('miaaaauw');
  19. };

幸运的是,在 Node.js 中可以使用新的 ES6 格式:

  1. class Pet {
  2. constructor(name) {
  3. this._name = name;
  4. }
  5. sayHello() {
  6. console.log('*scratch*');
  7. }
  8. get name() {
  9. return this._name;
  10. }
  11. }
  12. class Cat extends Pet {
  13. constructor(name) {
  14. super(name);
  15. }
  16. sayHello() {
  17. super.sayHello();
  18. console.log('miaaaauw');
  19. }
  20. }

有 extends 关键字、构造子、调用超类及属性,是不是很棒?还不止这些,看看 MDN 上的更详细的介绍。

3. 箭头函数

在函数里面对 this 的动态绑定总是会导致一些混乱,人们一般是这样用的:

  1. Cat.prototype.notifyListeners = function () {
  2. var self = this;
  3. this._listeners.forEach(function (listener) {
  4. self.notifyListener(listener);
  5. });
  6. };
  1. Cat.prototype.notifyListeners = function () {
  2. this._listeners.forEach(function (listener) {
  3. this.notifyListener(listener);
  4. }.bind(this));
  5. };

现在你可以使用胖箭头函数了:

  1. Cat.prototype.notifyListeners = function () {
  2. this._listeners.forEach((listener) => {
  3. this.notifyListener(listener);
  4. });
  5. };

了解箭头函数的更多细节。.

4. 对象字面量

使用对象字面量,你现在有了很漂亮的快捷方式:

  1. var age = 10, name = 'Petsy', size = 32;
  2. // 不要这样做 ...
  3. var cat = {
  4. age: age,
  5. name: name,
  6. size: size
  7. };
  8. // ... 而是这样做 ...
  9. var cat = {
  10. age,
  11. name,
  12. size
  13. };

此外,你现在可以很容易地 给你的对象字面量添加函数

5. Promise

不用再依赖像 bluebird 或 Q这样的第三方库了,你现在可以使用 原生的 promise. 它们公开了如下 API:

  1. var p1 = new Promise(function (resolve, reject) {});
  2. var p2 = Promise.resolve(20);
  3. var p3 = Promise.reject(new Error());
  4. var p4 = Promise.all(p1, p2);
  5. var p5 = Promise.race(p1, p2);
  6. // 显然
  7. p1.then(() => {}).catch(() => {});

6. 字符串方法

我们也有了一系列新的字符串功能:

  1. // 在几种情况下可以替代 `indexOf()`
  2. name.startsWith('a')
  3. name.endsWith('c');
  4. name.includes('b');
  5. // 重复字符串三次
  6. name.repeat(3);

去告诉那些使用 Ruby 的家伙吧!字符串现在也 对 unicode 支持更好了

7. let 和 const

猜猜下列函数调用的返回值:

  1. var x = 20;
  2. (function () {
  3. if (x === 20) {
  4. var x = 30;
  5. }
  6. return x;
  7. }()); // -> undefined

是的, undefined。使用 let 替代 var ,你会得到预期的行为:

  1. let x = 20;
  2. (function () {
  3. if (x === 20) {
  4. let x = 30;
  5. }
  6. return x;
  7. }()); // -> 20

原因是什么呢? var 是函数作用域,而 let 是块级作用域(如大部分人所预期的)。因此,可以说 let 是一个新var。 你可以在 MDN 上了解更多细节

此外,Node.js 也支持 const 关键字了,它可以防止你为同一个引用赋予不同的值:

  1. var MY_CONST = 42; // no, no
  2. const MY_CONST = 42; // yes, yes
  3. MY_CONST = 10 // 使用了 const ,这就不行了

结语

Node.js 4.0.0 带来了更多的 ES6 特性,我希望这七个例子可以吸引你升级到最新版本。

还有更多的语言特性呢(例如,maps/sets, 符号和生成器,这里只提到了一点)。你可以看看 Node.js 4.0.0 的 ES6 概览。 赶快升级吧!

TCP/IP协议栈及OSI参考模型详解

Standard

原文:http://wangdy.blog.51cto.com/3845563/1588379

OSI参考模型

OSI RM:开放系统互连参考模型(open systeminterconnection reference model)

OSI参考模型具有以下优点:

    • 简化了相关的网络操作;
    • 提供设备间的兼容性和标准接口;
    • 促进标准化工作;
    • 结构上可以分隔;
    • 易于实现和维护。

 

20世纪60年代以来,计算机网络得到了飞速增长。各大厂商为了在数据通信网络领域占据主导地    位,纷纷推出了各自的网络架构体系和标准,如IBM公司的SNA,Novell IPX/SPX协议,Apple公司的AppleTalk协议,DEC公司的DECnet,以及广泛流行的TCP/IP协议。同时,各大厂商针对自己的协议生产出了不同的硬件和软件。各个厂商的共同努力促进了网络技术的快速发展和网络设备种类的迅速增长。但由于多种协议的并存,也使网络变得越来越复杂;而且,厂商之间的网络设备大部分不能兼容,很难进行通信。

为了解决网络之间的兼容性问题,帮助各个厂商生产出可兼容的网络设备,国际标准化组织ISO于1984年提出了OSI RM(OpenSystem Interconnection Reference Model,开放系统互连参考模型)。OSI 参考模型很快成为计算机网络通信的基础模型。在设计OSI 参考模型时,遵循了以下原则:各个层之间有清晰的边界,实现特定的功能;层次的划分有利于国际标准协议的制定;层的数目应该足够多,以避免各个层功能重复。

 

OSI分层

 

wKioL1SIBIaiOFczAADimSwcq6s561.jpg

通常OSI参考模型第一层到第三层称为底层(lower layer),又叫介质层(media layer),底层负责数据在网络中的传送,网络互连设备往往位于下三层,以硬件和软件的方式来实现。OSI参考模型的第五层到第七层称为高层(upper layer),又叫住几层(host layer),高层用于保障数据的正确传输,以软件方式来实现。

 

OSI七层功能:

wKiom1SIA_nwv_AgAAHIC52DZA4848.jpg

 

  • TCP/IP协议栈

wKioL1SIBJKy7q8oAAEMHfbl-0E582.jpg

由于OSI模型和协议比较复杂,所以并没有得到广泛的应用。

而TCP/IP(transfer control protocol/internet protocol,传输控制协议/网际协议)模型因其开放性和易用性在实践中得到了广泛的应用,TCP/IP协议栈也成为互联网的主流协议。

wKiom1SIBAHw1MybAAE_fDStMQg817.jpg

TCP/IP模型各个层次分别对应于不同的协议。TCP/IP协议栈是数据通信协议的集合 ,包含许多协议。其协议栈名字来源于其中最主要的两个协议TCP(传输控制协议)和IP(网际协议)。TCP/IP协议栈负责确保网络设备之间能够通信。它是一组规则,规定了信息如何在网络中传输。

 

TCP/IP模型的层间通信与数据封装

 

wKiom1SIBN_iV-a8AAHEz78AQQE658.jpg

TCP/IP每一层都让数据得以通过网络进行传输,这些层之间使用PDU(协议数据单元)彼此交换信息,确保网络设备之间能够通信。

wKioL1SIBXngTSn2AAFtzBd_5_4918.jpg

A.    传输层数据中加入TCP报头后得到PDU被称为segment(数据段)

B.    数据段被传递给网络层,网络层添加IP报头得到的PDU被称为packet(数据包)

C.    数据包被传递到数据链路层,封装数据链路层报头得到的PDU被称为frame(数据帧)

D.    帧被转换为比特,通过网络介质传输。

这种协议栈向下传递数据,并添加报头和报尾的过程称为封装,数据被封装并通过网络传输后,接收设备将删除添加的信息,并根据报头中的信息决定如何将数据沿协议栈上传给合适的应用程序,这个过程称为解封装。不同设备的对等层之间依靠封装和解封装来实现相互间的通信。

 

 

物理层

物理层功能:

  • 规定介质类型、接口类型、信令类型;
  • 规范在终端系统之间激活、维护和关闭物理链路的电气、机械、流程和功能等方面的要求;
  • 规范电平、数据速率、最大传输距离和物理接头等特征。

wKiom1SIBOXxKFUYAACaTcRu0rw177.jpg

物理层标准规定了物理介质和用于将设备与物理介质相连的接头。

如上图,局域网常用的物理层标准有IEEE指定的以太网标准802.3、令牌总线标准802.4、令牌环网标准802.5以及美国国家标准组织ANSI的X3T9.5委员会制订的光缆标准FDDI(fiber distributed data interface,光纤分布式数据接口)等。广域网常用的物理层标准有电子工业协会和电信工业协会EIA/TIA制定的公共物理层接口标准EIA/TIA-232(即RS-232)、国际电信联盟ITU制定的串行线路接口标准V.24和V.35、以及有关各种数字接口的物理和电气特性的标准G.703等。

物理层介质和物理层设备:

  物理层介质:

    • 同轴电缆(coaxical cable)
    • 双绞线(twisted pair)
    • 光纤(fiber)
    • 无线电波(wireless raido)

 

同轴电缆:

wKiom1SIBdmQ2tgzAADxPQFWWRg801.jpg

同轴电缆是一种早期使用的传输介质,同轴电缆的标准分为两种,10BASE2和10BASE5.这两种标准都支持10Mbps的传输速率,最长传输距离分别为185米和500米。10BASE5和10BASE2的同轴电缆使用

的同轴电缆的直径分别为9.5mm和5mm,所以前者又称为粗缆,后者又称为细缆。一般情况下,10BASE2同轴电缆使用BNC接头,10BASE5同轴电缆使用N型接头。目前,10Mbps的传输速率早已不能满足目前企业网络需求,因此同轴电缆在目前企业网络中很少应用。

 

双绞线

wKiom1SIBOqRwiqQAAD9zkp39Q0530.jpg

双绞线采用了一对互相绝缘的金属导线互相绞合的方式来抵御一部分外界电磁波干扰。把两根绝缘的铜导线按一定密度互相绞在一起,可以降低信号干扰的程度,每一根导线在传输中辐射的电波会被另一根线上发出的电波抵消,“双绞线”的名字也是由此而来的。

 

与同轴电缆相比双绞线(twistedpair)具有更低的制造和部署成本,因此在企业网络中被广泛应用。双绞线可分为屏蔽双绞线(shieldedtwisted pair,STP)和非屏蔽双绞线(unshieldedtwisted pair,UTP)。屏蔽双绞线在双绞线与外层绝缘封套之间有一个金属屏蔽层,可以屏蔽电磁干扰。

 

双绞线有很多种类型,不同类型的 双绞线所支持的传输速率一般也不相同。例如,3类双绞线支持10Mbps传输速率;5类双绞线支持100Mbps传输速率,满足快速以太网标准;超5类双绞线及更高级别的双绞线支持千兆以太网传输。

 

双绞线线序:

568A线序:

1-绿白,2-绿,3-橙白,4-蓝,5-蓝白,6-橙,7-棕白,8-棕

568B线序:

1-橙白,2-橙,3-绿白,4-蓝,5-蓝白,6绿,7-棕白,8-棕

 

根据网线两端连接网络设备的不同,网线又分为直通线(平行线)和交叉线两种。

直通线(平行线)就是按照前面介绍的568A标准或568B标准制作(即双绞线两端的线序一样,568A的线序不常用,现主流用的都是568B的线序)

交叉线的一端保持原来的线序,另一端把1和3对调,2和5对调。

 

直通线和交叉线的应用:

1.    同种类型设备之间使用交叉线连接,不同类型设备之间使用直通线连接;

2.    路由器和PC属于DTE(DataTerminal Equipment,数据终端设备)类型设备,交换机和HUB数据DCE(Data Circuit-terminatingEquipment,数据通信设备)类型设备。

 

光纤

 

wKioL1SIBtTQDsL7AAHLv3k9JBw286.jpg

双绞线和同轴电缆传输数据时使用的是电信号,而光纤传输数据时使用的是光信号。光纤支持的传输速率包括10Mbps,100Mbps,1Gbps,10Gbps,甚至更高。根据光纤传输光信号模式的不同,光纤又可分为单模光纤和多模光纤。单模光纤只能传输一种模式的光,不存在模间色散,因此适用于长距离高速传输。多模光纤允许不同模式的光在一根光纤上传输,由于模间色散较大而导致信号脉冲展宽严重,因此多模光纤主要用于局域网中的短距离传输。光纤连接器种类喝多,常用的连接器包括ST,FC,SC,LC连接器。

 

串口电缆

wKioL1SIBtuh_7oPAAE_HOI2lt4917.jpg

网络通信中常常会用到各种各样的串口电缆。常用的串口电缆标准为RS-232,同时也是推荐的标准。但是RS-232的传输速率有限,传输距离仅为6米。其他的串口电缆标准可以支持更长的传输距离,例如RS-422和RS-485的传输距离可达1200米。RS-422和RS-485串口电缆通常使用V.35接头,这种接头在上世纪80年代已经淘汰,但是现在仍在帧中继、ATM等传统网络上使用。V.24是RS-232标准的欧洲版。RS-232本身没有定义接头标准,常用的接头类型为DB-9和DB-25。现在,RS-232已逐渐被FireWire、USB等新标准取代,新产品和新设备已普遍使用USB标准。

 

冲突域

wKiom1SIBkjjixwzAACvWv9IRbc487.jpg

如图是一个10BASE5以太网,每个主机都是用同一根同轴电缆来与其它主机进行通信,因此,这里的同轴电缆又被称为共享介质,相应的网络被称为共享介质网络,或简称为共享式网络。共享式网络中,不同的主机同时发送数据时,就会产生信号冲突的问题,解决这一问题的方法一般是采用载波侦听多路访问/冲突检测技术(carrier sense multiple access/collisiondetection)。

CSMA/CD的基本工作过程如下:

1.    终端不停地检测共享线路的状态。如果线路空闲,则可以发送数据;如果线路不空闲,则等待一段时间后继续检测(延时时间由退避算法决定)。

2.    如果有另一个设备同时发送数据,两个设备发送的数据会产生冲突。

3.    终端设备检测到冲突之后,马上停止发送自己的数据,并发送特殊阻塞信息,以强化冲突信号,使线路上其他站点能够尽早检测到冲突。

4.    终端设备检测到冲突后,等待一段时间之后再进行数据发送(延时时间由退避算法决定)。

CSMA/CD的工作原理可简单总结为:先听后发,边发边听,冲突停发,随机延迟后重发。

 

物理层设备:中继器和集线器

 

数据链路层

数据链路层又分为MAC子层和LLC子层

wKioL1SIBuDToShPAACwexBlz_8850.jpg

MACSub-layer:media access controlsub-layer介质访问控制子层

MAC子层负责指定数据如何通过物理线路进行传输,并向下与物理层通信,它定义了物理编址、网络拓扑、线路规范、错误通知、按序传递和流量控制等功能。

LLCSub-layer:logic link control sub-layer逻辑链路控制子层

LLC子层负责识别协议类型并对数据进行封装以便通过网络进行传输。LLC子层主要执行数据链路层的大部分功能和网络层的部分功能。如帧的收发功能,在发送时,帧由发送的数据加上地址和CRC校验等构成,接收时将帧拆开,执行地址识别、CRC校验,并具有帧顺序控制、差错控制、流量控制等功能。此外,它还执行数据报、虚电路、多路复用等部分网络层的功能。

 

数据链路层协议

wKiom1SIBk7Cs5SUAAFC3wxBffU801.jpg

数据链路层协议规定了数据链路层帧的封装方式。

局域网常用的数据链路层协议有IEEE802.2 LLC标准。

广域网常用的数据链路层协议有:

HDLC(high-level data link control,高级数据链路控制)

              PPP(point-to-point protocol,点到点协议)

              FR(frame relay,帧中继)

 

数据链路层-以太网地址(MAC地址)

wKiom1SIBlGzRYY_AADHj1rzMTc659.jpg

网络设备的MAC地址是全球唯一的。MAC地址由48个二进制位组成,通常我们用十六进制数字来表示。其中前6位十六进制数字由IEEE统一分配给设备制造商,后6位十六进制数字由厂商自行分配。

 

网络层

功能:在不同的网络之间转发数据包

    • 提供逻辑地址,如果数据跨网络传递,则需要使用逻辑地址来寻址。
    • 路由:将数据报文从一个网络转发到另一个网络。

设备:路由器、三层交换机

 

网络层协议

wKioL1SIBu2A4HS5AAFf0Wv8N9I094.jpg

常用网络层协议有:

IP(Internet Protocol):IP为网络层最主要的协议,其功能即为网络层的主要功能,一是提供逻辑编址,二是提供路由功能,三是报文的封装和解封装。ICMP、ARP、RARP协议辅助IP工作。

  ICMP(Internet Control Message Protocol)是一个管理协议并为IP提供信息服务,ICMP消息承载在IP报文中。

ARP(Address Resolution Protocol)实现IP地址到硬件地址的动态映射,即根据已知的IP地址获得相应的硬件地址。

RARP(Reverse Address Resolution Protocol)实现硬件地址到IP地址的动态映射,即根据已知的硬件地址获得相应的IP地址。

 

网络层地址:网络地址在网络层唯一标识一台网络设备。

网络地址包含两部分:网络ID+主机ID(下节主要内容)

 

传输层

主要功能:

    • 分段上层数据;
    • 建立端到端连接;
    • 将数据从一端主机传送到另一端主机;
    • 保证数据按序、可靠、正确传输。

传输层协议:

wKiom1SIBljRr48mAAFPpXRKpXU847.jpg

传输层协议主要包含传输控制协议TCP(transfer control protocol)和用户数据报文协议UDP(user datagram protocol)

 

wKiom1SIBzHSMZ78AAF3CFFhIxI894.jpg

TCP提供面向连接的、可靠的字节流服务。面向连接意味着使用TCP协议作为传输层协议的两个应用之间在相互交换数据之前必须建立一个TCP连接。TCP通过确认、校验、重组等机制为上层应用提供可靠的传输服务。但是TCP连接的建立以及确认、校验等机制都需要耗费大量的工作并且会带来大量的开销。

UDP提供简单的、面向数据报的服务。UDP不保证可靠性,即不保证报文能够到达目的地。UDP适用于更关注传输效率的应用,如SNMP、Radius等,SNMP监控网络并断续发送告警等消息,如果每次发送少量信息都需要建立TCP连接,无疑会降低传输效率,所以诸如SNMP、Radius等更注重传输效率的应用程序都会选择UDP作为传输层协议。另外,UDP还适用于本身具备可靠性机制的应用层协议。

 

应用层功能

    • 为用户提供接口、处理特定的应用;
    • 数据加密、解密、压缩、解压缩;
    • 定义数据表示的标准。

应用层协议

wKiom1SIBziAnfTLAAIEZXvr3G4915.jpg

应用层有许多协议,以下协议可以帮助您使用和管理 TCP/IP 网络:

FTP(File TransferProtocol) 文件传输协议。用于传输独立的文件,通常用于交互式用户会话。

HTTP(HypertextTransfer Protocol)超文本传输协议。 用于传输那些构成万维网上的页面的文件。

TELNET :远程终端访问。用于传送具有TELNET控制信息的数据。它提供了与终端设备或终端进程交互的标准方法,支持终端到终端的连接及进程到进程分布式计算的通信。

SMTP(Simple MessageTransfer Protocol)简单邮件传输协议 和

POP3(Post OfficeProtocol)邮局协议用于发送和接收邮件。

DNS(Domain NameServer)是一个域名服务的协议,提供域名到IP地址的转换,允许对域名资源进行分散管理。

TFTP(Trivial FileTransfer Protocol)简单文件传输协议。设计用于一般目的的、高吞吐量的文件传输。

RIP(RoutingInformation Protocol)路由器用来在 IP 网络上交换路由信息的协议。

SNMP(Simple NetworkManagement Protocol)用于收集网络管理信息,并在网络管理控制台和网络设备(例如路由器、网桥和服务器)之间交换网络管理信息。

Radius(RemoteAuthentication Dial In User Service)拨号接入远端认证协议完成接入用户的认证、授权、计费功能的协议。

 

  • TCP/IP协议栈的封装过程

wKioL1SIB9bQaJBVAAGxIUxvNyc832.jpg

以传输层采用TCP或者UPD、网络层采用IP、链路层采用Ethernet为例,可以看到TCP/IP中报文的封装过程如上图所示。用户数据经过应用层协议封装后传递给传输层,传输层封装TCP头部,交给网络层,网络层封装IP头部后,再交给数据链路层,数据链路层封装Ethernet帧头和帧尾,交给物理层,物理层以比特流的形式将数据发送到物理线路上。

 

TCP Segment

wKiom1SIB0CA7CtDAADq-b6k7KM867.jpg

TCP协议概述:

TCP为应用程序提供一种面向连接的、可靠的服务。

TCP的可靠性:

    • 面向连接的传输
    • 最大报文段长度
    • 传输确认机制
    • 首部和数据的检验和
    • 流量控制

TCP首部格式

wKiom1SIB0LBnFOsAAEujCB4yys663.jpg

TCP使用IP作为网络层协议,TCP数据段被封装在一个IP数据包内。TCP数据段由TCP Head(头部)和TCP Data(数据)组成。

TCP最多有60个字节的首部,如果没有任选字段,正常的长度是20字节。TCP Head如上图标识的一些字段组成,这里列出几个常用的字段。

16位源端口号:TCP会为源应用程序分配一个源端口号。

16位目的端口号:目的应用程序的端口号。每个TCP段都包含源和目的端的端口号,用于寻找发端和收端应用进程。这两个值加上IP首部中的源端IP地址和目的端IP地址可以唯一确定一个TCP连接。

32位序列号:用于标识从TCP发端向TCP收端发送的数据字节流。

32位确认序列号:确认序列号包含发送确认的一端所期望收到的下一个序号。确认序列号为上次成功收到的数据序列号加1。

4位首部长度:表示首部占32bit字的数目。因为TCP首部的最大长度为60字节。

16位窗口大小:表示接收端期望接收的字节,由于该字段为16位,因而窗口大小最大值为65535字节。

 16位检验和:检验和覆盖了整个TCP报文段,包括TCP首部和TCP数据。该值由发端计算和存储并由接收端进行验证。

 

TCP的三次握手(建立连接)和四次挥手(断开连接)

 

TCP连接的建立是一个三次握手的过程。如图所示:

wKioL1SIB9rCarKmAAC_CU7_mao308.jpg

1、请求端(通常也称为客户端)发送一个SYN段表示客户期望连接服务器端口,初始序列号为a。

2、服务器发回序列号为b的SYN段作为响应。同时设置确认序号为客户端的序列号加1(a+1)作为对客户端的SYN报文的确认。

3、客户端设置序列号为服务器端的序列号加1(b+1)作为对服务器端SYN报文段的确认。

这三个报文段完成TCP连接的建立。

 

TCP连接的建立是一个三次握手的过程,而TCP连接的终止则要经过四次握手。

如图所示:

wKiom1SIB0aiDqNnAADKHCMfIgI643.jpg

1、请求端(通常也称为客户端)想终止连接则发送一个FIN段,序列号设置为a。

2、服务器回应一个确认序号为客户端的序列号加1(a+1)的ACK确认段,作为对客户端的FIN报文的确认。

3、服务器端向客户端发送一个FIN终止段(设置序列号为b,确认号为a+1)。

4、客户端返回一个确认报文(设置序列号为b+1)作为响应。

以上四次交互完成双方向的连接的关闭。

 

TCP滑动窗口机制:

    wKioL1SIB-byaWruAAImM3ycikA350.jpg

TCP滑动窗口技术通过动态改变窗口大小来调节两台主机间的数据传输。每个TCP/IP主机支持全双工数据传输,因此TCP有两个滑动窗口:一个用于接收数据,另一个用于发送数据。TCP使用肯定确认技术,其确认号指的是下一个所期待的字节。

如图中所示以数据单方向发送为例,介绍滑动窗口如何实现流量

控制。服务器端向客户端发送4个大小为1024字节的数据段,其中发送端的窗口大小为4096,客户端到以ACK4097响应,窗口大小调整为2048,表明客户端(即接收端)缓冲区只能处理2048个字节的数据段。于是发送端改变其发送速率。发送接收端能够接收的数据段大小2048的数据段。

 

 

UDP协议概述

  • UDP为应用程序提供面向无连接的服务。传输数据之前源端和目的端不需要建立连接。
  • 不需要维持连接状态,收发状态等,因此服务器可同时向多个客户端传输相同的消息。
  • UDP适用于对传输效率要求高的运用。

UDP首部格式

 

wKiom1SIB8TRO_zhAADNA8HrkkQ733.jpg

UDP和TCP一样都使用IP作为网络层协议,TCP数据报被封装在一个IP数据包内。由于UDP不象TCP一样提供可靠的传输,因此UDP的报文格式相对而言较简单。

整个UDP首部有如下标识:

16位源端口号:为源端应用程序分配的一个源端口号。

16位目的端口号:目的应用程序的端口号

16位UDP长度:是指UDP首部和UDP数据的字节长度。该字段的最小值为8。

16位UDP检验和:该字段提供与TCP检验和同样的功能,只不过在UDP协议中该字段是可选的。

 

TCP VS UDP

wKioL1SICFyyZNXSAAFY4J3hgbU169.jpg

IP packet

wKiom1SIB8ugRyWwAAGRNKHx1IE758.jpg

网络层收到传输层的TCP数据段后会再加上网络层IP头部信息。普通的IP头部固定长度为20个字节(不包含IP选项字段)。

IP报文头主要由以下字段组成:报文长度是指头部占32比特字的个数,包括任何选项。由于它是一个4比特字段,24=16,除掉全0项共有15个有效值比特字段,其中最大值也为15,表示头部占15个32比特。因此32*15/8=60字节,头部最长为60字节。

版本号(Version)字段标明了IP协议的版本号,目前的协议版本号为4。下一代IP协议的版本号为6。

8比特的服务类型(TOS,Type of Service)字段包括一个3比特的优先权字段(COS,Class of Service),4比特TOS字段和1比特未用位。4比特TOS分别代表最小时延、最大吞吐量、最高可靠性和最小费用。

总长度(Total length)是整个IP数据报长度,包括数据部分。由于该字段长16比特,所以IP数据报最长可达65535字节。尽管可以传送一个长达65535字节的IP数据报,但是大多数的链路层都会对它进行分片。而且,主机也要求不能接收超过576字节的数据报。UDP限制用户数据报长度为512字节,小于576字节。而事实上现在大多数的实现(特别是那些支持网络文件系统NFS的实现)允许超过8192字节的IP数据报。

标识符(Identification)字段唯一地标识主机发送的每一份数据包。通常每发送一份报文它的值就会加1。

生存时间(TTL,Time to Live)字段设置了数据包可以经过的路由器数目。一旦经过一个路由器,TTL值就会减1,当该字段值为0时,数据包将被丢弃。

协议字段确定在数据包内传送的上层协议,和端口号类似,IP协议用协议号区分上层协议。TCP协议的协议号为6,UDP协议的协议号为17。

报头校验和(Head checksum)字段计算IP头部的校验和,检查报文头部的完整性。

源IP地址和目的IP地址字段标识数据包的源端设备和目的端设备IP地址信息。

Ethernet frame

wKiom1SIB9CgS-M7AAEfkSYePsA236.jpg

以太网头部由三个字段组成:

DMAC:表示目的终端MAC地址。

SMAC:表示源端MAC地址。

LENGTH/TYPE字段:根据值的不同有不同的含义:

当LENGHT/TYPE > 1500时,代表该数据帧的类型(比如

上层协议类型)常见的协议类型有:

0X0800 IP数据包

0X0806 ARP请求/应答报文

0X8035 RARP请求/应答报文。

当LENGTH/TYPE < 1500时,代表该数据帧的长度。

 

案例分析

wKiom1SIFQ-AU8LgAABPLDaZkWk637.jpg

如上图所示,通过例举出的TELNET协议的抓包实例,进一步加深对报文封装的理解。

wKioL1SIFaeiK8bgAAKorRwk0sc836.jpg

上图为AR1使用TELNET协议远程登录AR2进行的TCP三次握手过程。

wKioL1SIFajAi0-nAAHJcfjBW4s739.jpg

上图为数据链路层封装。如图可知使用的是Ethernet II格式封装。

DMAC为:00e0:fc3b:6792

SMAC为:00e0:fc80:64f3

type:字段为0x0800表明数据字段封装是IP报文。

wKiom1SIFRTiFYjwAALqjueaz2o705.jpg

上图为网络层报文封装。一个网络层IP包是由IP头部和IP数据组成。

上图表明是一个IPv4的报文

报文头为20字节

协议字段为0x06,表明数据封装的是一个TCP报文。

数据的源IP地址为12.12.12.1,目的IP地址为12.12.12.2

wKioL1SIFazyFJs8AAJF_RjjIv8392.jpg

上图为传输层数据封装。如图所示的传输层使用的是TCP协议

源端口号为随机端口号49895,目的端口号为公认TELNET协议端口号23


附:

常用默认端口号 网络层—数据包的包格式里面有个很重要的字段叫做协议号。比如在传输层如果是TCP连接那么在网络层IP包里面的协议号就将会有个值是6如果是UDP的话那个值就是17—传输层。

传输层—通过接口关联(端口的字段叫做端口)—应用层。

用netstat –an 可以查看本机开放的端口号。

代理服务器常用以下端口:

HTTP协议代理服务器常用端口号80/8080/3128/8081/9080

SOCKS代理协议服务器常用端口号1080

FTP文件传输协议代理服务器常用端口号21

Telnet远程登录协议代理服务器常用端口23

HTTP服务器默认的端口号为80/tcp木马Executor开放此端口

HTTPSsecurely transferring web pages服务器默认的端口号为443/tcp 443/udp

Telnet不安全的文本传送默认端口号为23/tcp木马Tiny Telnet Server所开放的端口

FTP默认的端口号为21/tcp木马Doly Trojan、Fore、InvisibleFTP、WebEx、WinCrash和Blade Runner所开放的端口

TFTPTrivial File Transfer Protocol 默认的端口号为69/udp

SSH安全登录、SCP文件传输、端口重定向默认的端口号为22/tcp

SMTP Simple Mail Transfer Protocol (E-mail)默认的端口号为25/tcp木马Antigen、EmailPassword Sender、Haebu Coceda、ShtrilitzStealth、WinPC、WinSpy都开放这个端口

POP3 Post Office Protocol (E-mail) 默认的端口号为110/tcp

WebLogic默认的端口号为7001

Webshpere应用程序默认的端口号为9080

webshpere管理工具默认的端口号为9090

JBOSS默认的端口号为8080

TOMCAT默认的端口号为8080

WIN2003远程登陆默认的端口号为3389

Symantec AV/Filter for MSE ,默认端口号为8081 Oracle 数据库默认的端口号为1521

ORACLE EMCTL默认的端口号为1158

Oracle XDB XML 数据库默认的端口号为8080

Oracle XDB FTP服务默认的端口号为2100

MS SQL*SERVER数据库server默认的端口号为1433/tcp 1433/udp

MS SQL*SERVER数据库monitor默认的端口号为1434/tcp 1434/udp

QQ默认的端口号为1080/u

Web网页性能管理详解

Standard

原文:http://www.ruanyifeng.com/blog/2015/09/web-page-performance-in-depth.html

你遇到过性能很差的网页吗?

这种网页响应非常缓慢,占用大量的 CPU 和内存,浏览起来常常有卡顿,页面的动画效果也不流畅。

你会有什么反应?我猜想,大多数用户会关闭这个页面,改为访问其他网站。作为一个开发者,肯定不愿意看到这种情况,怎样才能提高性能呢?

本文将详细介绍性能问题的出现原因,以及解决方法。

一、网页生成的过程

要理解网页性能为什么不好,就要了解网页是怎么生成的。

网页的生成过程,大致可以分成五步。

  • HTML 代码转化成 DOM
  • CSS 代码转化成 CSSOM(CSS Object Model)
  • 结合 DOM 和 CSSOM,生成一棵渲染树(包含每个节点的视觉信息)
  • 生成布局(layout),即将所有渲染树的所有节点进行平面合成
  • 将布局绘制(paint)在屏幕上

这五步里面,第一步到第三步都非常快,耗时的是第四步和第五步。

“生成布局”(flow)和”绘制”(paint)这两步,合称为”渲染”(render)。

二、重排和重绘

网页生成的时候,至少会渲染一次。用户访问的过程中,还会不断重新渲染。

以下三种情况,会导致网页重新渲染。

  • 修改 DOM
  • 修改样式表
  • 用户事件(比如鼠标悬停、页面滚动、输入框键入文字、改变窗口大小等等)

重新渲染,就需要重新生成布局和重新绘制。前者叫做”重排”(reflow),后者叫做”重绘”(repaint)。

需要注意的是,”重绘”不一定需要”重排”,比如改变某个网页元素的颜色,就只会触发”重绘”,不会触发”重排”,因为布局没有改变。但是,”重排”必然导致”重绘”,比如改变一个网页元素的位置,就会同时触发”重排”和”重绘”,因为布局改变了。

三、对于性能的影响

重排和重绘会不断触发,这是不可避免的。但是,它们非常耗费资源,是导致网页性能低下的根本原因。

提高网页性能,就是要降低”重排”和”重绘”的频率和成本,尽量少触发重新渲染。

前面提到,DOM 变动和样式变动,都会触发重新渲染。但是,浏览器已经很智能了,会尽量把所有的变动集中在一起,排成一个队列,然后一次性执行,尽量避免多次重新渲染。

div.style.color = 'blue';
div.style.marginTop = '30px';

上面代码中,div 元素有两个样式变动,但是浏览器只会触发一次重排和重绘。

如果写得不好,就会触发两次重排和重绘。

div.style.color = 'blue';
var margin = parseInt (div.style.marginTop);
div.style.marginTop = (margin + 10) + 'px';

上面代码对 div 元素设置背景色以后,第二行要求浏览器给出该元素的位置,所以浏览器不得不立即重排。

一般来说,样式的写操作之后,如果有下面这些属性的读操作,都会引发浏览器立即重新渲染。

  • offsetTop/offsetLeft/offsetWidth/offsetHeight
  • scrollTop/scrollLeft/scrollWidth/scrollHeight
  • clientTop/clientLeft/clientWidth/clientHeight
  • getComputedStyle ()

所以,从性能角度考虑,尽量不要把读操作和写操作,放在一个语句里面。

// bad
div.style.left = div.offsetLeft + 10 + "px";
div.style.top = div.offsetTop + 10 + "px";

// good
var left = div.offsetLeft;
var top  = div.offsetTop;
div.style.left = left + 10 + "px";
div.style.top = top + 10 + "px";

一般的规则是:

  1. 样式表越简单,重排和重绘就越快。
  2. 重排和重绘的 DOM 元素层级越高,成本就越高。
  3. table 元素的重排和重绘成本,要高于 div 元素

四、提高性能的九个技巧

有一些技巧,可以降低浏览器重新渲染的频率和成本。

第一条是上一节说到的,DOM 的多个读操作(或多个写操作),应该放在一起。不要两个读操作之间,加入一个写操作。

第二条,如果某个样式是通过重排得到的,那么最好缓存结果。避免下一次用到的时候,浏览器又要重排。

第三条,不要一条条地改变样式,而要通过改变 class,或者 csstext 属性,一次性地改变样式。

// bad
var left = 10;
var top = 10;
el.style.left = left + "px";
el.style.top  = top  + "px";

// good 
el.className += " theclassname";

// good
el.style.cssText += "; left: " + left + "px; top: " + top + "px;";

第四条,尽量使用离线 DOM,而不是真实的网面 DOM,来改变元素样式。比如,操作 Document Fragment 对象,完成后再把这个对象加入 DOM。再比如,使用 cloneNode () 方法,在克隆的节点上进行操作,然后再用克隆的节点替换原始节点。

第五条,先将元素设为 display: none (需要 1 次重排和重绘),然后对这个节点进行 100 次操作,最后再恢复显示(需要 1 次重排和重绘)。这样一来,你就用两次重新渲染,取代了可能高达 100 次的重新渲染。

第六条,position 属性为 absolute 或 fixed 的元素,重排的开销会比较小,因为不用考虑它对其他元素的影响。

第七条,只在必要的时候,才将元素的 display 属性为可见,因为不可见的元素不影响重排和重绘。另外,visibility : hidden 的元素只对重排有影响,不影响重绘。

第八条,使用虚拟 DOM 的脚本库,比如 React 等。

第九条,使用 window.requestAnimationFrame ()、window.requestIdleCallback () 这两个方法调节重新渲染(详见后文)。

五、刷新率

很多时候,密集的重新渲染是无法避免的,比如 scroll 事件的回调函数和网页动画。

网页动画的每一帧(frame)都是一次重新渲染。每秒低于 24 帧的动画,人眼就能感受到停顿。一般的网页动画,需要达到每秒 30 帧到 60 帧的频率,才能比较流畅。如果能达到每秒 70 帧甚至 80 帧,就会极其流畅。

大多数显示器的刷新频率是 60Hz,为了与系统一致,以及节省电力,浏览器会自动按照这个频率,刷新动画(如果可以做到的话)。

所以,如果网页动画能够做到每秒 60 帧,就会跟显示器同步刷新,达到最佳的视觉效果。这意味着,一秒之内进行 60 次重新渲染,每次重新渲染的时间不能超过 16.66 毫秒。

一秒之间能够完成多少次重新渲染,这个指标就被称为”刷新率”,英文为 FPS(frame per second)。60 次重新渲染,就是 60FPS。

六、开发者工具的 Timeline 面板

Chrome 浏览器开发者工具的 Timeline 面板,是查看”刷新率”的最佳工具。这一节介绍如何使用这个工具。

首先,按下 F12 打开”开发者工具”,切换到 Timeline 面板。

左上角有一个灰色的圆点,这是录制按钮,按下它会变成红色。然后,在网页上进行一些操作,再按一次按钮完成录制。

Timeline 面板提供两种查看方式:横条的是”事件模式”(Event Mode),显示重新渲染的各种事件所耗费的时间;竖条的是”帧模式”(Frame Mode),显示每一帧的时间耗费在哪里。

先看”事件模式”,你可以从中判断,性能问题发生在哪个环节,是 JavaScript 的执行,还是渲染?

不同的颜色表示不同的事件。

  • 蓝色:网络通信和 HTML 解析
  • 黄色:JavaScript 执行
  • 紫色:样式计算和布局,即重排
  • 绿色:重绘

哪种色块比较多,就说明性能耗费在那里。色块越长,问题越大。

帧模式(Frames mode)用来查看单个帧的耗时情况。每帧的色柱高度越低越好,表示耗时少。

你可以看到,帧模式有两条水平的参考线。

下面的一条是 60FPS,低于这条线,可以达到每秒 60 帧;上面的一条是 30FPS,低于这条线,可以达到每秒 30 次渲染。如果色柱都超过 30FPS,这个网页就有性能问题了。

此外,还可以查看某个区间的耗时情况。

或者点击每一帧,查看该帧的时间构成。

七、window.requestAnimationFrame ()

有一些 JavaScript 方法可以调节重新渲染,大幅提高网页性能。

其中最重要的,就是 window.requestAnimationFrame () 方法。它可以将某些代码放到下一次重新渲染时执行。

function doubleHeight (element) {
  var currentHeight = element.clientHeight;
  element.style.height = (currentHeight * 2) + 'px';
}
elements.forEach (doubleHeight);

上面的代码使用循环操作,将每个元素的高度都增加一倍。可是,每次循环都是,读操作后面跟着一个写操作。这会在短时间内触发大量的重新渲染,显然对于网页性能很不利。

我们可以使用window.requestAnimationFrame (),让读操作和写操作分离,把所有的写操作放到下一次重新渲染。

function doubleHeight (element) {
  var currentHeight = element.clientHeight;
  window.requestAnimationFrame (function () {
    element.style.height = (currentHeight * 2) + 'px';
  });
}
elements.forEach (doubleHeight);

页面滚动事件(scroll)的监听函数,就很适合用 window.requestAnimationFrame () ,推迟到下一次重新渲染。

$(window) .on ('scroll', function() {
   window.requestAnimationFrame (scrollHandler);
});

当然,最适用的场合还是网页动画。下面是一个旋转动画的例子,元素每一帧旋转 1 度。

var rAF = window.requestAnimationFrame;

var degrees = 0;
function update () {
  div.style.transform = "rotate (" + degrees + "deg)";
  console.log ('updated to degrees ' + degrees);
  degrees = degrees + 1;
  rAF (update);
}
rAF (update);

八、window.requestIdleCallback ()

还有一个函数 window.requestIdleCallback (),也可以用来调节重新渲染。

它指定只有当一帧的末尾有空闲时间,才会执行回调函数。

requestIdleCallback (fn);

上面代码中,只有当前帧的运行时间小于 16.66ms 时,函数 fn 才会执行。否则,就推迟到下一帧,如果下一帧也没有空闲时间,就推迟到下下一帧,以此类推。

它还可以接受第二个参数,表示指定的毫秒数。如果在指定的这段时间之内,每一帧都没有空闲时间,那么函数 fn 将会强制执行。

requestIdleCallback (fn, 5000);

上面的代码表示,函数 fn 最迟会在 5000 毫秒之后执行。

函数 fn 可以接受一个 deadline 对象作为参数。

requestIdleCallback (function someHeavyComputation (deadline) {
  while(deadline.timeRemaining () > 0) {
    doWorkIfNeeded ();
  }

  if(thereIsMoreWorkToDo) {
    requestIdleCallback (someHeavyComputation);
  }
});

上面代码中,回调函数 someHeavyComputation 的参数是一个 deadline 对象。

deadline 对象有一个方法和一个属性:timeRemaining () 和 didTimeout。

(1)timeRemaining () 方法

timeRemaining () 方法返回当前帧还剩余的毫秒。这个方法只能读,不能写,而且会动态更新。因此可以不断检查这个属性,如果还有剩余时间的话,就不断执行某些任务。一旦这个属性等于0,就把任务分配到下一轮requestIdleCallback

前面的示例代码之中,只要当前帧还有空闲时间,就不断调用 doWorkIfNeeded 方法。一旦没有空闲时间,但是任务还没有全执行,就分配到下一轮requestIdleCallback

(2)didTimeout 属性

deadline 对象的 didTimeout 属性会返回一个布尔值,表示指定的时间是否过期。这意味着,如果回调函数由于指定时间过期而触发,那么你会得到两个结果。

  • timeRemaining 方法返回0
  • didTimeout 属性等于 true

因此,如果回调函数执行了,无非是两种原因:当前帧有空闲时间,或者指定时间到了。

function myNonEssentialWork (deadline) {
  while ((deadline.timeRemaining () > 0 || deadline.didTimeout) && tasks.length > 0)
    doWorkIfNeeded ();

  if (tasks.length > 0)
    requestIdleCallback (myNonEssentialWork);
}

requestIdleCallback (myNonEssentialWork, 5000);

上面代码确保了,doWorkIfNeeded 函数一定会在将来某个比较空闲的时间(或者在指定时间过期后)得到反复执行。

requestIdleCallback 是一个很新的函数,刚刚引入标准,目前只有 Chrome 支持。

九、参考链接

使用脚本便捷地在 Ubuntu 中安装最新 Linux 内核

Standard

原文:http://ubuntuhandbook.org/index.php/2015/08/install-latest-kernel-script/作者: Ji m
译文:LCTT  https://linux.cn/article-6219-1.html译者: mr-ping

--------

想要安装最新的Linux内核吗?一个简单的脚本就可以在Ubuntu系统中方便的完成这项工作。

Michael Murphy 写了一个脚本用来将最新的候选版、标准版、或者低延时版的内核安装到 Ubuntu 系统中。这个脚本会在询问一些问题后从 Ubuntu 内核主线页面 下载安装最新的 Linux 内核包。

通过脚本来安装、升级Linux内核:

1、 点击这个 github 页面 右上角的 “Download Zip” 来下载该脚本(注:此脚本在墙外,我已经搬运回来了,请参见下面。)。

2、鼠标右键单击用户下载目录下的 Zip 文件,选择 “在此展开” 将其解压。

3、右键点击解压后的文件夹,选择 “在终端中打开” 到此文件夹下。

此时将会打开一个终端,并且自动导航到目标文件夹下。如果你找不到 “在终端中打开” 选项的话,在 Ubuntu 软件中心搜索安装 nautilus-open-terminal ,然后重新登录系统即可(也可以再终端中运行 nautilus -q 来取代重新登录系统的操作)。

备注:此脚本如下,你可以将它保存为一个可执行的 shell 脚本:

  1. #!/bin/bash
  2. cd /tmp
  3. if ! which lynx > /dev/null; then sudo apt-get install lynx -y; fi
  4. if [ "$(getconf LONG_BIT)" == "64" ]; then arch=amd64; else arch=i386; fi
  5. function download() {
  6. wget $(lynx -dump -listonly -dont-wrap-pre $kernelURL | grep "$1" | grep "$2" | grep "$arch" | cut -d ' ' -f 4)
  7. }
  8. # Kernel URL
  9. read -p "Do you want the latest RC?" rc
  10. case "$rc" in
  11. y* | Y*) kernelURL=$(lynx -dump -nonumbers http://kernel.ubuntu.com/~kernel-ppa/mainline/ | tail -1) ;;
  12. n* | N*) kernelURL=$(lynx -dump -nonumbers http://kernel.ubuntu.com/~kernel-ppa/mainline/ | grep -v rc | tail -1) ;;
  13. *) exit ;;
  14. esac
  15. read -p "Do you want the lowlatency kernel?" lowlatency
  16. case "$lowlatency" in
  17. y* | Y*) lowlatency=1 ;;
  18. n* | n*) lowlatency=0 ;;
  19. *) exit ;;
  20. esac
  21. # Download Kernel
  22. if [ "$lowlatency" == "0" ]; then
  23. echo "Downloading the latest generic kernel."
  24. download generic header
  25. download generic image
  26. elif [ "$lowlatency" == "1" ]; then
  27. echo "Downloading the latest lowlatency kernel."
  28. download lowlatency header
  29. download lowlatency image
  30. fi
  31. # Shared Kernel Header
  32. wget $(lynx -dump -listonly -dont-wrap-pre $kernelURL | grep all | cut -d ' ' -f 4)
  33. # Install Kernel
  34. echo "Installing Linux Kernel"
  35. sudo dpkg -i linux*.deb
  36. echo "Done. You may now reboot."

4. 当进入终端后,运行以下命令来赋予脚本执行本次操作的权限。

  1. chmod +x *

最后,每当你想要安装或升级 Ubuntu 的 linux 内核时都可以运行此脚本。

  1. ./*

这里之所以使用 * 替代脚本名称是因为文件夹中只有它一个文件。

如果脚本运行成功,重启电脑即可。

恢复并且卸载新版内核

如果因为某些原因要恢复并且移除新版内核的话,请重启电脑,在 Grub 启动器的 高级选项 菜单下选择旧版内核来启动系统。

当系统启动后,参照下边章节继续执行。

如何移除旧的(或新的)内核:

  1. 从 Ubuntu 软件中心安装 Synaptic Package Manager。
  2. 打开 Synaptic Package Manager 然后如下操作:
  • 点击 Reload 按钮,让想要被删除的新内核显示出来.
  • 在左侧面板中选择 Status -> Installed ,让查找列表更清晰一些。
  • 在 Quick filter 输入框中输入 linux-image- 用于查询。
  • 选择一个内核镜像 “linux-image-x.xx.xx-generic” 然后将其标记为removal(或者Complete Removal)
  • 最后,应用变更

重复以上操作直到移除所有你不需要的内核。注意,不要随意移除此刻正在运行的内核,你可以通过 uname -r 命令来查看运行的内核。

对于 Ubuntu 服务器来说,你可以一步步运行下面的命令:

  1. uname -r
  2. dpkg -l | grep linux-image-
  3. sudo apt-get autoremove KERNEL_IMAGE_NAME


via: http://ubuntuhandbook.org/index.php/2015/08/install-latest-kernel-script/