GVKun编程网logo

Swift 个人学习笔记 - 01: A Swift Tour(swift入门)

3

针对Swift个人学习笔记-01:ASwiftTour和swift入门这两个问题,本篇文章进行了详细的解答,同时本文还将给你拓展ASwiftTour、Android个人学习笔记-导入android项目

针对Swift 个人学习笔记 - 01: A Swift Tourswift入门这两个问题,本篇文章进行了详细的解答,同时本文还将给你拓展A Swift Tour、Android 个人学习笔记- 导入android项目,无法自动生成R文件的解决方法、android 个人学习笔记:Unable to open sync connection! 异常处理、Chapter_9 DP : uva1347 tour (bitonic tour)等相关知识,希望可以帮助到你。

本文目录一览:

Swift 个人学习笔记 - 01: A Swift Tour(swift入门)

Swift 个人学习笔记 - 01: A Swift Tour(swift入门)

本文章纯粹是中文版《The Swift Programming Language》的学习笔记,所以绝大部分的内容都是文中有的。本文是本人的学习笔记,不是正式系统的记录。仅供参考

以下还是有很多没看懂、不确定的地方,我会以“存疑”的注解指出。

在此感谢中文版翻译者,这极大地加快了 Swift 的学习速度。

Reference:

原版:The Swift Programming Language
中文版:Swift 3 编程语言

几个无法分类的知识:
1 - Swift 不需要 main()函数,全局的第一段代码就是程序的入口。(存疑)
2 - Swift 中没有像 C 里面一样,非常明确地区别“声明”和“定义”的概念,全部的定义都是 “声明 + 定义”。

变量和常量

声明变量和常量

let aConstant = 42
let aConstantDouble : Double = 70   // 个人推荐

这样根据后面的值假定常量的类型。第一个例子里面,常量的类型就被设置成了Int。而第二个例子里面,虽然初始化值给的是一个Int,但是前面显式地说明了这是一个Double类型变量,所以这就是一个 Double 类型。

变量使用的是var

数组

在 Swift 里面,数组和关联数组成为了基本数据类型(在 Objective-C 里面是类),这大大简化了数据操作。
声明方式如下:

var shoppingList = ["catfish","water","popcorn"]
var shoppingList = [String]()

其中第一行是定义+初始值。第二行则不赋予初始值

关联数组(Dictionary)

var aDict = [:]
var aDict = [String:Float]()        // 推荐
var alistofSalaries = [
    "Andrew": 10000.0,"Bob": 15000.0
]

上面第二种方法是详细的定义,具体限制了关联数组的 key 和 value 的类型。

控制流

基本上和 C 差不多,但不需要括号。不过有{}
条件操作有:ifswitch
循环操作有:for-inforwhilerepeat-while(不是 “do-while”)。

注意if的条件不循序用一个普通变量的值作为判断条件体了,只能布尔判断值。比如 “if some_value” 就是不合法的写法。

Optional 变量

如果声明变量的时候加入?,那么变量就是可选的(optional)
此时,变量可以置为 nil 值。

猜测这个方法就是相当于 C 里面的指针或者是其他方法中的引用(不确定)。

Arrar 和 Dictionary 中的 for-in

for number in someArray {
    ...
}

for (kind,number) in someDictionary {
    ...
}

上面是使用 “for-in” 语法来 access array 和 dict 的方法。当然,array 和 dict 也可以嵌套。

循环

while n < 200 { ... }

repeat { ... } while m < 100

for i in 0..<4 {   }         // 表示 [0,4)
for i in 0...4 {   }         // 表示 [0,4]

函数和簇(闭包)

使用 func 来声明和定义函数:

func greeting (persion: String,day: String) -> String {
    ...
}

可以使用 “元组”(tuple)来创建仅在该函数中使用的复合值(类似 struct):

func calculate (scores:[Int]) -> (min: Int,max: Int,sum: Int) {
    ...
}

此外,可以把函数作为值返回:

func theFunc(number: Int) -> Int { ... }

func retuanAFunc() -> (Int -> Int) {
    return theFunc
}

函数可以内嵌,内嵌的函数可以访问外部的变量:

func someFunc() -> Int {
    var error: Int = 0
    ...
    func checkerror() {
        if (...) { error = -1 }
    }
    ...
    return error
}

对象和类

使用关键字 class 加花括号来构建一个类。与前面其他格式中花括号的作用一眼,都只是用来作为作用域。

var anInstance = aClass    // 很像 C++

使用点语法来访问类中的成员与方法。

初始化函数:init,接近 Objective-C 中的 init
反初始化函数:deinit,接近 Objective-C 中的 dealloc
成员函数重载:在 func 前面加上 override 关键字。

getter / setter

声明成员时,额外可以声明 getter / setter:

class SomeClass : FatherClass {
    var radius : Int
    init (radius : Int) {
        super.init (radius)
        self.radius = radius
    }
    
    var circle : Double {
        get {
            ...
        }
        set {
            ...        // setter的参数如果未定义的话,默认叫做 `newValue`。也可以显式地定义。
        }
    }
}

willset 和 didSet

有时候,如果不需要自行实现 set / get操作,但需要在值更新前后操作的话,可以针对该值定义 willSetdidSet 函数:

var squre : Double {
    willSet: {
        ...
    }
}

枚举和结构体

这其实是我最搞不懂的元素之一了,目测我以后只会用最基础的部分。
使用 enum 创建枚举。enum 可以包括函数:

enum PokerFace {
    case ace = 1            // 注意这里如果不赋初始值的话,默认是 1
    case two,three,four,five,six,seven,eight,nine,ten
    case jack,queen,king
    func decription() -> String {
        switch self {
            case .ace:
                return "ace"
            case .jack:
                return "jack"
            case .queen:
                return "queen"
            case .king:
                return "king"
            default:
            return String (self.rawValue)        // Note
        }
    }
}

注意隐含的 rawValue 值。

可以用构造函数创建一个 enum 的实例:

let arank = Rank (rawValue : 3)
let arank = Rank (.three)

使用 struct 定义结构体:

struct Card_st {
    var rank : Rank
    var suit : Suit
    func simpleDescription () -> String {
        return ...
    }
}

struct 的行为与 class 很类似,但传递时,struct 传递的是拷贝,而 class 传递的是引用
struct 也有 initializer

协议和扩展

协议

protocol ExampleProtocol {
    var simpleDescription: String {get}
    mutating func adjust ()
}

声明部分的两行分别代表一下意思:

  1. 有一个针对 simpleDescritpion 的 String 的 getter

  2. 声明一个函数:其中 mutating 关键字用在 struct 中,表示可以修改 struct 的内容。

class、struct 和 enum 都可以有协议。

声明一个类,表示符合某个协议,在冒号后面加就好了:

class SomeClass : ExampleProtocol {
    ...
}

扩展

extansion Int: ExampleExtansion {
    ...
}

上面表示为 Int 类型添加一个名为 “ExampleExtension” 的扩展。

此时你可以创建一个叫做 “ExampleProtocol” 的 Int 变量,这个时候, “ExampleExtension” 的语义就变成了 “添加了 ExampleExtension 扩展的 Int 类型”。这是的基本类型也好像类一样继承了。

错误处理

使用遵循 Error 协议的类型来表示错误,比如:

enum ExampleError : Error {
    case outOfPaper
    case noToner
    case onFire
}

使用 throw 来抛出错误。使用 throws 标记可以抛出错误的函数:

func send (job : Int,toPrinter printerName : String) throws -> String {
    ...
    if printerName == ... {
        throw ExampleError.noToner
    }
    return "..."
}

错误处理方法1:do-catch

do {
    ...
} catch {
    print(error)        // 这个貌似是隐含的数据类型?不确定
}

错误处理方法2:do + 多个catch

do {
    ...
} catch PrinterError.onFire {
    ...
} catch let printerError as PrinterError {
    print ("Printer error: \(printerError).")
} catch {
    print(error)
}

错误处理方法3:try?
没明白

下一篇

Swift 个人学习笔记 - 02: 基础内容

A Swift Tour

A Swift Tour

Tradition suggests that the first program in a new language should print the words “Hello,world!” on the screen. In Swift,this can be done in a single line:

  1. print("Hello,world!")

If you have written code in C or Objective-C,this Syntax looks familiar to you—in Swift,this line of code is a complete program. You don’t need to import a separate library for functionality like input/output or string handling. Code written at global scope is used as the entry point for the program,so you don’t need amain()function. You also don’t need to write semicolons at the end of every statement.

This tour gives you enough information to start writing code in Swift by showing you how to accomplish a variety of programming tasks. Don’t worry if you don’t understand something—everything introduced in this tour is explained in detail in the rest of this book.

NOTE

For the best experience,open this chapter as a playground in Xcode. Playgrounds allow you to edit the code listings and see the result immediately.

Download Playground

Simple Values

Useletto make a constant andvarto make a variable. The value of a constant doesn’t need to be kNown at compile time,but you must assign it a value exactly once. This means you can use constants to name a value that you determine once but use in many places.

  1. var myVariable = 42
  2. myVariable = 50
  3. let myConstant = 42

A constant or variable must have the same type as the value you want to assign to it. However,you don’t always have to write the type explicitly. Providing a value when you create a constant or variable lets the compiler infer its type. In the example above,the compiler infers thatmyVariableis an integer because its initial value is an integer.

If the initial value doesn’t provide enough information (or if there is no initial value),specify the type by writing it after the variable,separated by a colon.

  1. let implicitInteger = 70
  2. let implicitDouble = 70.0
  3. let explicitDouble: Double = 70

EXPERIMENT

Create a constant with an explicit type ofFloatand a value of4.

Values are never implicitly converted to another type. If you need to convert a value to a different type,explicitly make an instance of the desired type.

  1. let label = "The width is "
  2. let width = 94
  3. let widthLabel = label + String(width)

EXPERIMENT

Try removing the conversion toStringfrom the last line. What error do you get?

There’s an even simpler way to include values in strings: Write the value in parentheses,and write a backslash (\) before the parentheses. For example:

  1. let apples = 3
  2. let oranges = 5
  3. let appleSummary = "I have \(apples) apples."
  4. let fruitSummary = "I have \(apples + oranges) pieces of fruit."

EXPERIMENT

Use\()to include a floating-point calculation in a string and to include someone’s name in a greeting.

Create arrays and dictionaries using brackets ([]),and access their elements by writing the index or key in brackets. A comma is allowed after the last element.

  1. var shoppingList = ["catfish","water","tulips","blue paint"]
  2. shoppingList[1] = "bottle of water"
  3. var occupations = [
  4. "Malcolm": "Captain",
  5. "Kaylee": "Mechanic",
  6. ]
  7. occupations["Jayne"] = "Public Relations"

To create an empty array or dictionary,use the initializer Syntax.

  1. let emptyArray = [String]()
  2. let emptyDictionary = [String: Float]()

If type information can be inferred,you can write an empty array as[]and an empty dictionary as[:]—for example,when you set a new value for a variable or pass an argument to a function.

  1. shoppingList = []
  2. occupations = [:]

Control Flow

Useifandswitchto make conditionals,and usefor-in,for,while,andrepeat-whileto make loops. Parentheses around the condition or loop variable are optional. Braces around the body are required.

  1. let individualscores = [75,43,103,87,12]
  2. var teamscore = 0
  3. for score in individualscores {
  4. if score > 50 {
  5. teamscore += 3
  6. } else {
  7. teamscore += 1
  8. }
  9. }
  10. print(teamscore)

In anifstatement,the conditional must be a Boolean expression—this means that code such asif score { ... }is an error,not an implicit comparison to zero.

You can useifandlettogether to work with values that might be missing. These values are represented as optionals. An optional value either contains a value or containsnilto indicate that a value is missing. Write a question mark (?) after the type of a value to mark the value as optional.

  1. var optionalString: String? = "Hello"
  2. print(optionalString == nil)
  3. var optionalName: String? = "John Appleseed"
  4. var greeting = "Hello!"
  5. if let name = optionalName {
  6. greeting = "Hello,\(name)"
  7. }

EXPERIMENT

ChangeoptionalNametonil. What greeting do you get? Add anelseclause that sets a different greeting ifoptionalNameisnil.

If the optional value isnil,the conditional isfalseand the code in braces is skipped. Otherwise,the optional value is unwrapped and assigned to the constant afterlet,which makes the unwrapped value available inside the block of code.

Another way to handle optional values is to provide a default value using the??operator. If the optional value is missing,the default value is used instead.

  1. let nickName: String? = nil
  2. let fullName: String = "John Appleseed"
  3. let informalGreeting = "Hi \(nickName ?? fullName)"

Switches support any kind of data and a wide variety of comparison operations—they aren’t limited to integers and tests for equality.

  1. let vegetable = "red pepper"
  2. switch vegetable {
  3. case "celery":
  4. print("Add some raisins and make ants on a log.")
  5. case "cucumber","watercress":
  6. print("That would make a good tea sandwich.")
  7. case let x where x.hasSuffix("pepper"):
  8. print("Is it a spicy \(x)?")
  9. default:
  10. print("Everything tastes good in soup.")
  11. }

EXPERIMENT

Try removing the default case. What error do you get?

Notice howletcan be used in a pattern to assign the value that matched the pattern to a constant.

After executing the code inside the switch case that matched,the program exits from the switch statement. Execution doesn’t continue to the next case,so there is no need to explicitly break out of the switch at the end of each case’s code.

You usefor-into iterate over items in a dictionary by providing a pair of names to use for each key-value pair. Dictionaries are an unordered collection,so their keys and values are iterated over in an arbitrary order.

  1. let interestingNumbers = [
  2. "Prime": [2,3,5,7,11,13],
  3. "Fibonacci": [1,1,2,8],
  4. "Square": [1,4,9,16,25],
  5. ]
  6. var largest = 0
  7. for (kind,numbers) in interestingNumbers {
  8. for number in numbers {
  9. if number > largest {
  10. largest = number
  11. }
  12. }
  13. }
  14. print(largest)

EXPERIMENT

Add another variable to keep track of which kind of number was the largest,as well as what that largest number was.

Usewhileto repeat a block of code until a condition changes. The condition of a loop can be at the end instead,ensuring that the loop is run at least once.

  1. var n = 2
  2. while n < 100 {
  3. n = n * 2
  4. }
  5. print(n)
  6. var m = 2
  7. repeat {
  8. m = m * 2
  9. } while m < 100
  10. print(m)

You can keep an index in a loop by using..<to make a range of indexes.

  1. var total = 0
  2. for i in 0..<4 {
  3. total += i
  4. }
  5. print(total)

Use..<to make a range that omits its upper value,and use...to make a range that includes both values.

Functions and Closures

Usefuncto declare a function. Call a function by following its name with a list of arguments in parentheses. Use->to separate the parameter names and types from the function’s return type.

  1. func greet(person: String,day: String) -> String {
  2. return "Hello \(person),today is \(day)."
  3. }
  4. greet(person: "Bob",day: "Tuesday")

EXPERIMENT

Remove thedayparameter. Add a parameter to include today’s lunch special in the greeting.

By default,functions use their parameter names as labels for their arguments. Write a custom argument label before the parameter name,or write_to use no argument label.

  1. func greet(_ person: String,on day: String) -> String {
  2. return "Hello \(person),today is \(day)."
  3. }
  4. greet("John",on: "Wednesday")

Use a tuple to make a compound value—for example,to return multiple values from a function. The elements of a tuple can be referred to either by name or by number.

  1. func calculateStatistics(scores: [Int]) -> (min: Int,max: Int,sum: Int) {
  2. var min = scores[0]
  3. var max = scores[0]
  4. var sum = 0
  5. for score in scores {
  6. if score > max {
  7. max = score
  8. } else if score < min {
  9. min = score
  10. }
  11. sum += score
  12. }
  13. return (min,max,sum)
  14. }
  15. let statistics = calculateStatistics(scores: [5,100,9])
  16. print(statistics.sum)
  17. print(statistics.2)

Functions can also take a variable number of arguments,collecting them into an array.

  1. func sumOf(numbers: Int...) -> Int {
  2. var sum = 0
  3. for number in numbers {
  4. sum += number
  5. }
  6. return sum
  7. }
  8. sumOf()
  9. sumOf(numbers: 42,597,12)

EXPERIMENT

Write a function that calculates the average of its arguments.

Functions can be nested. nested functions have access to variables that were declared in the outer function. You can use nested functions to organize the code in a function that is long or complex.

  1. func returnFifteen() -> Int {
  2. var y = 10
  3. func add() {
  4. y += 5
  5. }
  6. add()
  7. return y
  8. }
  9. returnFifteen()

Functions are a first-class type. This means that a function can return another function as its value.

  1. func makeIncrementer() -> ((Int) -> Int) {
  2. func addOne(number: Int) -> Int {
  3. return 1 + number
  4. }
  5. return addOne
  6. }
  7. var increment = makeIncrementer()
  8. increment(7)

A function can take another function as one of its arguments.

  1. func hasAnyMatches(list: [Int],condition: (Int) -> Bool) -> Bool {
  2. for item in list {
  3. if condition(item) {
  4. return true
  5. }
  6. }
  7. return false
  8. }
  9. func lessthanTen(number: Int) -> Bool {
  10. return number < 10
  11. }
  12. var numbers = [20,19,12]
  13. hasAnyMatches(list: numbers,condition: lessthanTen)

Functions are actually a special case of closures: blocks of code that can be called later. The code in a closure has access to things like variables and functions that were available in the scope where the closure was created,even if the closure is in a different scope when it is executed—you saw an example of this already with nested functions. You can write a closure without a name by surrounding code with braces ({}). Useinto separate the arguments and return type from the body.

  1. numbers.map({
  2. (number: Int) -> Int in
  3. let result = 3 * number
  4. return result
  5. })

EXPERIMENT

Rewrite the closure to return zero for all odd numbers.

You have several options for writing closures more concisely. When a closure’s type is already kNown,such as the callback for a delegate,you can omit the type of its parameters,its return type,or both. Single statement closures implicitly return the value of their only statement.

  1. let mappednumbers = numbers.map({ number in 3 * number })
  2. print(mappednumbers)

You can refer to parameters by number instead of by name—this approach is especially useful in very short closures. A closure passed as the last argument to a function can appear immediately after the parentheses. When a closure is the only argument to a function,you can omit the parentheses entirely.

  1. let sortednumbers = numbers.sorted { $0 > $1 }
  2. print(sortednumbers)

Objects and Classes

Useclassfollowed by the class’s name to create a class. A property declaration in a class is written the same way as a constant or variable declaration,except that it is in the context of a class. Likewise,method and function declarations are written the same way.

  1. class Shape {
  2. var numberOfSides = 0
  3. func simpleDescription() -> String {
  4. return "A shape with \(numberOfSides) sides."
  5. }
  6. }

EXPERIMENT

Add a constant property withlet,and add another method that takes an argument.

Create an instance of a class by putting parentheses after the class name. Use dot Syntax to access the properties and methods of the instance.

  1. var shape = Shape()
  2. shape.numberOfSides = 7
  3. var shapeDescription = shape.simpleDescription()

This version of theShapeclass is missing something important: an initializer to set up the class when an instance is created. Useinitto create one.

  1. class NamedShape {
  2. var numberOfSides: Int = 0
  3. var name: String
  4. init(name: String) {
  5. self.name = name
  6. }
  7. func simpleDescription() -> String {
  8. return "A shape with \(numberOfSides) sides."
  9. }
  10. }

Notice howselfis used to distinguish thenameproperty from thenameargument to the initializer. The arguments to the initializer are passed like a function call when you create an instance of the class. Every property needs a value assigned—either in its declaration (as withnumberOfSides) or in the initializer (as withname).

Usedeinitto create a deinitializer if you need to perform some cleanup before the object is deallocated.

Subclasses include their superclass name after their class name,separated by a colon. There is no requirement for classes to subclass any standard root class,so you can include or omit a superclass as needed.

Methods on a subclass that override the superclass’s implementation are marked withoverride—overriding a method by accident,withoutoverride,is detected by the compiler as an error. The compiler also detects methods withoverridethat don’t actually override any method in the superclass.

  1. class Square: NamedShape {
  2. var sideLength: Double
  3. init(sideLength: Double,name: String) {
  4. self.sideLength = sideLength
  5. super.init(name: name)
  6. numberOfSides = 4
  7. }
  8. func area() -> Double {
  9. return sideLength * sideLength
  10. }
  11. override func simpleDescription() -> String {
  12. return "A square with sides of length \(sideLength)."
  13. }
  14. }
  15. let test = Square(sideLength: 5.2,name: "my test square")
  16. test.area()
  17. test.simpleDescription()

EXPERIMENT

Make another subclass ofNamedShapecalledCirclethat takes a radius and a name as arguments to its initializer. Implement anarea()and asimpleDescription()method on theCircleclass.

In addition to simple properties that are stored,properties can have a getter and a setter.

  1. class EquilateralTriangle: NamedShape {
  2. var sideLength: Double = 0.0
  3. init(sideLength: Double,name: String) {
  4. self.sideLength = sideLength
  5. super.init(name: name)
  6. numberOfSides = 3
  7. }
  8. var perimeter: Double {
  9. get {
  10. return 3.0 * sideLength
  11. }
  12. set {
  13. sideLength = newValue / 3.0
  14. }
  15. }
  16. override func simpleDescription() -> String {
  17. return "An equilateral triangle with sides of length \(sideLength)."
  18. }
  19. }
  20. var triangle = EquilateralTriangle(sideLength: 3.1,name: "a triangle")
  21. print(triangle.perimeter)
  22. triangle.perimeter = 9.9
  23. print(triangle.sideLength)

In the setter forperimeter,the new value has the implicit namenewValue. You can provide an explicit name in parentheses afterset.

Notice that the initializer for theEquilateralTriangleclass has three different steps:

  1. Setting the value of properties that the subclass declares.

  2. Calling the superclass’s initializer.

  3. Changing the value of properties defined by the superclass. Any additional setup work that uses methods,getters,or setters can also be done at this point.

If you don’t need to compute the property but still need to provide code that is run before and after setting a new value,usewillSetanddidSet. The code you provide is run any time the value changes outside of an initializer. For example,the class below ensures that the side length of its triangle is always the same as the side length of its square.

  1. class TriangleAndSquare {
  2. var triangle: EquilateralTriangle {
  3. willSet {
  4. square.sideLength = newValue.sideLength
  5. }
  6. }
  7. var square: Square {
  8. willSet {
  9. triangle.sideLength = newValue.sideLength
  10. }
  11. }
  12. init(size: Double,name: String) {
  13. square = Square(sideLength: size,name: name)
  14. triangle = EquilateralTriangle(sideLength: size,name: name)
  15. }
  16. }
  17. var triangleAndSquare = TriangleAndSquare(size: 10,name: "another test shape")
  18. print(triangleAndSquare.square.sideLength)
  19. print(triangleAndSquare.triangle.sideLength)
  20. triangleAndSquare.square = Square(sideLength: 50,name: "larger square")
  21. print(triangleAndSquare.triangle.sideLength)

When working with optional values,you can write?before operations like methods,properties,and subscripting. If the value before the?isnil,everything after the?is ignored and the value of the whole expression isnil. Otherwise,the optional value is unwrapped,and everything after the?acts on the unwrapped value. In both cases,the value of the whole expression is an optional value.

  1. let optionalSquare: Square? = Square(sideLength: 2.5,name: "optional square")
  2. let sideLength = optionalSquare?.sideLength

Enumerations and Structures

Useenumto create an enumeration. Like classes and all other named types,enumerations can have methods associated with them.

  1. enum Rank: Int {
  2. case ace = 1
  3. case two,three,four,five,six,seven,eight,nine,ten
  4. case jack,queen,king
  5. func simpleDescription() -> String {
  6. switch self {
  7. case .ace:
  8. return "ace"
  9. case .jack:
  10. return "jack"
  11. case .queen:
  12. return "queen"
  13. case .king:
  14. return "king"
  15. default:
  16. return String(self.rawValue)
  17. }
  18. }
  19. }
  20. let ace = Rank.ace
  21. let aceRawValue = ace.rawValue

EXPERIMENT

Write a function that compares twoRankvalues by comparing their raw values.

By default,Swift assigns the raw values starting at zero and incrementing by one each time,but you can change this behavior by explicitly specifying values. In the example above,Aceis explicitly given a raw value of1,and the rest of the raw values are assigned in order. You can also use strings or floating-point numbers as the raw type of an enumeration. Use therawValueproperty to access the raw value of an enumeration case.

Use theinit?(rawValue:)initializer to make an instance of an enumeration from a raw value.

  1. if let convertedRank = Rank(rawValue: 3) {
  2. let threeDescription = convertedRank.simpleDescription()
  3. }

The case values of an enumeration are actual values,not just another way of writing their raw values. In fact,in cases where there isn’t a meaningful raw value,you don’t have to provide one.

  1. enum Suit {
  2. case spades,hearts,diamonds,clubs
  3. func simpleDescription() -> String {
  4. switch self {
  5. case .spades:
  6. return "spades"
  7. case .hearts:
  8. return "hearts"
  9. case .diamonds:
  10. return "diamonds"
  11. case .clubs:
  12. return "clubs"
  13. }
  14. }
  15. }
  16. let hearts = Suit.hearts
  17. let heartsDescription = hearts.simpleDescription()

EXPERIMENT

Add acolor()method toSuitthat returns “black” for spades and clubs,and returns “red” for hearts and diamonds.

Notice the two ways that theheartscase of the enumeration is referred to above: When assigning a value to theheartsconstant,the enumeration caseSuit.heartsis referred to by its full name because the constant doesn’t have an explicit type specified. Inside the switch,the enumeration case is referred to by the abbreviated form.heartsbecause the value ofselfis already kNown to be a suit. You can use the abbreviated form anytime the value’s type is already kNown.

If an enumeration has raw values,those values are determined as part of the declaration,which means every instance of a particular enumeration case always has the same raw value. Another choice for enumeration cases is to have values associated with the case—these values are determined when you make the instance,and they can be different for each instance of an enumeration case. You can think of the associated values as behaving like stored properties of the enumeration case instance. For example,consider the case of requesting the sunrise and sunset times from a server. The server either responds with the requested information,or it responds with a description of what went wrong.

  1. enum ServerResponse {
  2. case result(String,String)
  3. case failure(String)
  4. }
  5. let success = ServerResponse.result("6:00 am","8:09 pm")
  6. let failure = ServerResponse.failure("Out of cheese.")
  7. switch success {
  8. case let .result(sunrise,sunset):
  9. print("Sunrise is at \(sunrise) and sunset is at \(sunset).")
  10. case let .failure(message):
  11. print("Failure... \(message)")
  12. }

EXPERIMENT

Add a third case toServerResponseand to the switch.

Notice how the sunrise and sunset times are extracted from theServerResponsevalue as part of matching the value against the switch cases.

Usestructto create a structure. Structures support many of the same behaviors as classes,including methods and initializers. 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.

  1. struct Card {
  2. var rank: Rank
  3. var suit: Suit
  4. func simpleDescription() -> String {
  5. return "The \(rank.simpleDescription()) of \(suit.simpleDescription())"
  6. }
  7. }
  8. let threeOfSpades = Card(rank: .three,suit: .spades)
  9. let threeOfSpadesDescription = threeOfSpades.simpleDescription()

EXPERIMENT

Add a method toCardthat creates a full deck of cards,with one card of each combination of rank and suit.

Protocols and Extensions

Useprotocolto declare a protocol.

  1. protocol ExampleProtocol {
  2. var simpleDescription: String { get }
  3. mutating func adjust()
  4. }

Classes,enumerations,and structs can all adopt protocols.

  1. class SimpleClass: ExampleProtocol {
  2. var simpleDescription: String = "A very simple class."
  3. var anotherProperty: Int = 69105
  4. func adjust() {
  5. simpleDescription += " Now 100% adjusted."
  6. }
  7. }
  8. var a = SimpleClass()
  9. a.adjust()
  10. let aDescription = a.simpleDescription
  11. struct SimpleStructure: ExampleProtocol {
  12. var simpleDescription: String = "A simple structure"
  13. mutating func adjust() {
  14. simpleDescription += " (adjusted)"
  15. }
  16. }
  17. var b = SimpleStructure()
  18. b.adjust()
  19. let bDescription = b.simpleDescription

EXPERIMENT

Write an enumeration that conforms to this protocol.

Notice the use of themutatingkeyword in the declaration ofSimpleStructureto mark a method that modifies the structure. The declaration ofSimpleClassdoesn’t need any of its methods marked as mutating because methods on a class can always modify the class.

Useextensionto 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.

  1. extension Int: ExampleProtocol {
  2. var simpleDescription: String {
  3. return "The number \(self)"
  4. }
  5. mutating func adjust() {
  6. self += 42
  7. }
  8. }
  9. print(7.simpleDescription)

EXPERIMENT

Write an extension for theDoubletype that adds anabsoluteValueproperty.

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.

  1. let protocolValue: ExampleProtocol = a
  2. print(protocolValue.simpleDescription)
  3. // print(protocolValue.anotherProperty) // Uncomment to see the error

Even though the variableprotocolValuehas a runtime type ofSimpleClass,the compiler treats it as the given type ofExampleProtocol. This means that you can’t accidentally access methods or properties that the class implements in addition to its protocol conformance.

Error Handling

You represent errors using any type that adopts theErrorprotocol.

  1. enum PrinterError: Error {
  2. case outOfPaper
  3. case noToner
  4. case onFire
  5. }

Usethrowto throw an error andthrowsto mark a function that can throw an error. If you throw an error in a function,the function returns immediately and the code that called the function handles the error.

  1. func send(job: Int,toPrinter printerName: String) throws -> String {
  2. if printerName == "Never Has Toner" {
  3. throw PrinterError.noToner
  4. }
  5. return "Job sent"
  6. }

There are several ways to handle errors. One way is to usedo-catch. Inside thedoblock,you mark code that can throw an error by writingtryin front of it. Inside thecatchblock,the error is automatically given the nameerrorunless you give it a different name.

  1. do {
  2. let printerResponse = try send(job: 1040,toPrinter: "Bi Sheng")
  3. print(printerResponse)
  4. } catch {
  5. print(error)
  6. }

EXPERIMENT

Change the printer name to"Never Has Toner",so that thesend(job:toPrinter:)function throws an error.

You can provide multiplecatchblocks that handle specific errors. You write a pattern aftercatchjust as you do aftercasein a switch.

  1. do {
  2. let printerResponse = try send(job: 1440,toPrinter: "Gutenberg")
  3. print(printerResponse)
  4. } catch PrinterError.onFire {
  5. print("I'll just put this over here,with the rest of the fire.")
  6. } catch let printerError as PrinterError {
  7. print("Printer error: \(printerError).")
  8. } catch {
  9. print(error)
  10. }

EXPERIMENT

Add code to throw an error inside thedoblock. What kind of error do you need to throw so that the error is handled by the firstcatchblock? What about the second and third blocks?

Another way to handle errors is to usetry?to convert the result to an optional. If the function throws an error,the specific error is discarded and the result isnil. Otherwise,the result is an optional containing the value that the function returned.

  1. let printerSuccess = try? send(job: 1884,toPrinter: "Mergenthaler")
  2. let printerFailure = try? send(job: 1885,toPrinter: "Never Has Toner")

Usedeferto write a block of code that is executed after all other code in the function,just before the function returns. The code is executed regardless of whether the function throws an error. You can usedeferto write setup and cleanup code next to each other,even though they need to be executed at different times.

  1. var fridgeIsOpen = false
  2. let fridgeContent = ["milk","eggs","leftovers"]
  3. func fridgeContains(_ food: String) -> Bool {
  4. fridgeIsOpen = true
  5. defer {
  6. fridgeIsOpen = false
  7. }
  8. let result = fridgeContent.contains(food)
  9. return result
  10. }
  11. fridgeContains("banana")
  12. print(fridgeIsOpen)

Generics

Write a name inside angle brackets to make a generic function or type.

  1. func makeArray<Item>(repeating item: Item,numberOfTimes: Int) -> [Item] {
  2. var result = [Item]()
  3. for _ in 0..<numberOfTimes {
  4. result.append(item)
  5. }
  6. return result
  7. }
  8. makeArray(repeating: "knock",numberOfTimes:4)

You can make generic forms of functions and methods,as well as classes,and structures.

  1. // Reimplement the Swift standard library's optional type
  2. enum OptionalValue<Wrapped> {
  3. case none
  4. case some(Wrapped)
  5. }
  6. var possibleInteger: OptionalValue<Int> = .none
  7. possibleInteger = .some(100)

Usewhereright before the body to specify a list of requirements—for example,to require the type to implement a protocol,to require two types to be the same,or to require a class to have a particular superclass.

  1. func anyCommonElements<T: Sequence,U: Sequence>(_ lhs: T,_ rhs: U) -> Bool
  2. where T.Iterator.Element: Equatable,T.Iterator.Element == U.Iterator.Element {
  3. for lhsItem in lhs {
  4. for rhsItem in rhs {
  5. if lhsItem == rhsItem {
  6. return true
  7. }
  8. }
  9. }
  10. return false
  11. }
  12. anyCommonElements([1,3],[3])

EXPERIMENT

Modify theanyCommonElements(_:_:)function to make a function that returns an array of the elements that any two sequences have in common.

Writing<T: Equatable>is the same as writing<T> ... where T: Equatable.

Android 个人学习笔记- 导入android项目,无法自动生成R文件的解决方法

Android 个人学习笔记- 导入android项目,无法自动生成R文件的解决方法

从网上下载源码导进eclipse后,发现该有的jar包都有以后,就是无法在gen目录下生成R文件。

假如你也遇到这样的问题,你也许可以这样做,先点击project,然后选择clean一下;

 

然后打开project.properties文件,修改target=android-17(这个改为对应你自己的版本)即可,然后就会自动生成R文件!



android 个人学习笔记:Unable to open sync connection! 异常处理

android 个人学习笔记:Unable to open sync connection! 异常处理

Unable to open sync connection! 异常处理的方法:先关闭 USB 调试,然后再开 USB 调试。

Chapter_9 DP : uva1347 tour (bitonic tour)

Chapter_9 DP : uva1347 tour (bitonic tour)

https://cn.vjudge.net/problem/UVA-1347

这道题居然可以O(n^2)解决,让我太吃惊了!!!

鄙人见识浅薄,这其实是一个经典问题: bitonic tour.

它的定义是:

从最左点走到最右点在走回来,不重复经过点,最小需要多少路程.

在最左点走到最右点的过程中,只走到比当前点x坐标大的点,反之同理. (在该题中,没有两个点x坐标重复)

要得出\(O(n^2)\)的DP算法,需要几步转化:

首先,计算从左到右再回来的路径长度很麻烦(因为这样回来时要标记所有走过的点,状态\(2^n\)),不可行.
可以看成有两个人从最左点出发,经过不同的路径,最后都走到了最右点.

然后,为了防止集合的标记,我们定义以下状态:
\[ f(i,j) 表示 1... \max(i,j)都经过,第一个人到达i,第二个人到达j的最短路长度.\不妨设i>j.(请思考) \]
这样我们就无需标记经过的点了.

因为每次每个人都在向右走,所以只要讨论一下是那个人走到了\(i+1\)就可以了.

这就是状态转移方程:

f[i+1][i] = min(f[i+1][i],f[i][j] + dist(j,i+1));
            f[i+1][j] = min(f[i+1][j],f[i][j] + dist(i,i+1));

其实,"向右走" 就是一个天然的"序". 这就可以让该dp满足"无后效性"原则
这也就是TSP不能用这种方法的原因.

为何我们不会漏掉可能的情况?
思考一下,是不是每一条走完{1..n}的路线都存在一个走完{1..i}(i<n)的子路线? 所以不会漏.

code

#include<bits/stdc++.h>
using namespace std;

typedef long long ll;
#define rep(_i,_st,_ed) for(int _i = (_st); _i <= (_ed); ++_i)
#define per(_i,_ed,_st) for(int _i = (_ed); _i >= (_st); --_i)
inline int read(){int ans = 0,f = 1; char c = getchar();while(c < ‘0‘ || c > ‘9‘) f = (c == ‘-‘) ? -1 : f,c = getchar();while(‘0‘ <= c && c <= ‘9‘) ans = ans*10 + c - ‘0‘,c = getchar();return ans;}

const int maxn = 1005;
double f[maxn][maxn];
struct poi{
    double x,y;
    bool operator < (const poi &rhs) const{
        return x < rhs.x;
    }
}p[maxn];
int n;
#define sqr(_x) ((_x)*(_x))
double dist(int a,int b){
    return sqrt(sqr(p[a].x-p[b].x) + sqr(p[a].y - p[b].y));
}

signed main(){
    while(cin >> n) {
        rep(i,1,n) cin >> p[i].x >> p[i].y;

        if(n == 1) {
            puts("0.00"); 
            continue;
        }

        sort(p+1,p+n+1);
        rep(i,n) rep(j,n) f[i][j] = 1e10;
        
        //i > j
        f[2][1] = dist(1,2);

        rep(i,2,i-1){
            f[i+1][i] = min(f[i+1][i],i+1));
        }
        printf("%.2f\n",f[n][n-1] + dist(n,n-1));
    }
    return 0;
}

关于Swift 个人学习笔记 - 01: A Swift Tourswift入门的问题我们已经讲解完毕,感谢您的阅读,如果还想了解更多关于A Swift Tour、Android 个人学习笔记- 导入android项目,无法自动生成R文件的解决方法、android 个人学习笔记:Unable to open sync connection! 异常处理、Chapter_9 DP : uva1347 tour (bitonic tour)等相关内容,可以在本站寻找。

本文标签: