zoukankan      html  css  js  c++  java
  • 学习 swift (1)

    https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/DevelopiOSAppsSwift/Lesson1.html#//apple_ref/doc/uid/TP40015214-CH3-SW1

    这个链接里面介绍的 swift 的语法大部分都很容易理解。对于部分特别的地方做下记录

    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. Structures are great for defining lightweight data types that don’t need to have capabilities like inheritance and type casting.

    这里对 struct 和 class 做了比较

        struct 和 class 都有自己的 methods 和 initializers

        struct 和 class 最重要的区别在于:变量传递(赋值/传参)时,struct 是值传递(也就是拷贝,C++ 也是如此),而 class 是传引用(类似 Java)

        如果不需要考虑 继承和类型转换,那么用 struct 比较合适

    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.

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

    简单说,protocol 就是定义了一组 methods, properties balabala的类,不过 protocol 是用来被继承的,被 class, structure, enumeration 继承。实现了 protocal 里的那些东西,就符合这个 protocol。大概可以看成是一种接口吧。

    {get} 表示 read-only

    不带花括号的函数 adjust 就是声明来让继承 ExampleProtocol 的 class/struct/enumeration 实现的。

    delegate 和 protocol 相关链接 http://haoxiang.org/2011/08/ios-delegate-and-protocol/

    附上练习代码

      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)
     11 
     12 var optionalName: String? = "John Appleseed"
     13 var greeting = "Hello!"
     14 var optionalHello: String? = "Hello"
     15 
     16 if let hello = optionalHello where hello.hasPrefix("H"), let name = optionalName {
     17     greeting = "(hello), (name)"
     18 }
     19 print(greeting)
     20 
     21 let vegetable = "red pepper"
     22 var vegetableComment: String?
     23 switch vegetable {
     24     case "celery":
     25         vegetableComment = "Add some raisins and make ants on a log."
     26     case "cucumber", "watercress":
     27         vegetableComment = "That would make a good tea sandwich."
     28     case let x where x.hasSuffix("pepper"):
     29         vegetableComment = "Is it a spicy (x)?"
     30     default:
     31         vegetableComment = "Everything tastes good in soup."
     32 }
     33 print(vegetableComment)
     34 
     35 var firstForLoop = 0
     36 for i in 0..<4 {
     37     firstForLoop += i
     38 }
     39 print(firstForLoop)
     40 
     41 var secondForLoop = 0
     42 for _ in 0...4 {
     43     secondForLoop += 1
     44 }
     45 print(secondForLoop)
     46 
     47 
     48 func greet(name: String, day: String) -> String {
     49     return "Hello (name), today is (day)."
     50 }
     51 print(greet("hangj", day: "Thursday"))
     52 
     53 let exampleString = "hello"
     54 if exampleString.hasSuffix("lo") {
     55     print("ends in lo")
     56 }
     57 
     58 var array = ["apple", "banana", "dragonfruit"]
     59 array.insert("cherry", atIndex: 2)
     60 print(array)
     61 
     62 class Shape {
     63     var numberOfSides = 0
     64     func simpleDescription() -> String {
     65         return "A shape with (numberOfSides) sides."
     66     }
     67 }
     68 var shape = Shape()
     69 shape.numberOfSides = 7
     70 var shapeDescription = shape.simpleDescription()
     71 print(shapeDescription)
     72 
     73 class NamedShape {
     74     var numberOfSides = 0
     75     var name: String
     76 
     77     init(name: String) {
     78         self.name = name
     79     }
     80 
     81     func simpleDescription() -> String {
     82         return "A shape with (numberOfSides) sides."
     83     }
     84 }
     85 let namedShape = NamedShape(name: "my named shape")
     86 print(namedShape.simpleDescription())
     87 
     88 class Square: NamedShape {
     89     var sideLength: Double
     90 
     91     init(sideLength: Double, name: String){
     92         self.sideLength = sideLength
     93         super.init(name: name)
     94         numberOfSides = 4
     95     }
     96 
     97     func area() -> Double {
     98         return sideLength * sideLength
     99     }
    100 
    101     override func simpleDescription() -> String {
    102         return "A suqare with sides of length (sideLength)."
    103     }
    104 }
    105 let testSquare = Square(sideLength: 5.2, name: "my test square")
    106 print(testSquare.area())
    107 print(testSquare.simpleDescription())
    108 
    109 class Circle: NamedShape {
    110     var radius: Double
    111 
    112     init?(radius: Double, name: String) {
    113         self.radius = radius
    114         super.init(name: name)
    115         numberOfSides = 1
    116         if radius <= 0 {
    117             return nil
    118         }
    119     }
    120 
    121     override func simpleDescription() -> String {
    122         return "A circle with a radius of (radius)."
    123     }
    124 }
    125 if let successfulCircle = Circle(radius: 4.2, name: "successful circle") {
    126     print(successfulCircle.simpleDescription())
    127 }
    128 let failedCircle = Circle(radius: -7, name: "failed circle")
    129 
    130 class Triangle: NamedShape {
    131     init(sideLength: Double, name: String) {
    132         super.init(name: name)
    133         numberOfSides = 3
    134     }
    135 }
    136 let shapesArray = [Triangle(sideLength: 1.5, name: "triangle1"),
    137     Triangle(sideLength: 4.2, name: "triangle2"), Square(sideLength: 3.2, name: "square1"),
    138     Square(sideLength: 2.7, name: "square2")]
    139 var squares = 0
    140 var triangles = 0
    141 for shape in shapesArray {
    142     if let square = shape as? Square {
    143         ++squares
    144     } else if let triangle = shape as? Triangle {
    145         ++triangles
    146     }
    147 }
    148 print("(squares) squares and (triangles) triangles.")
    149 
    150 enum Rank: Int {
    151     case Ace = 1
    152     case Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten
    153     case Jack, Queen, King
    154     func simpleDescription() -> String {
    155         switch self {
    156             case .Ace:
    157                 return "ace"
    158             case .Jack:
    159                 return "jack"
    160             case .Queen:
    161                 return "queen"
    162             case .King:
    163                 return "king"
    164             default:
    165                 return String(self.rawValue)
    166         }
    167     }
    168 }
    169 let ace = Rank.Ace
    170 print(ace.simpleDescription())
    171 
    172 enum Suit {
    173     case Spades, Hearts, Diamonds, Clubs
    174     func simpleDescription() -> String {
    175         switch self {
    176             case .Spades:
    177                 return "Spades"
    178             case .Hearts:
    179                 return "hearts"
    180             case .Diamonds:
    181                 return "diamonds"
    182             case .Clubs:
    183                 return "clubs"
    184         }
    185     }
    186 }
    187 let hearts = Suit.Hearts
    188 let heartsDescription = hearts.simpleDescription()
    189 print(heartsDescription)
    190 
    191 struct Card {
    192     var rank: Rank
    193     var suit: Suit
    194     func simpleDescription() -> String {
    195         return "The (rank.simpleDescription()) of (suit.simpleDescription())"
    196     }
    197 }
    198 let threeOfSpades = Card(rank: .Three, suit: .Spades)
    199 let threeOfSpadesDescription = threeOfSpades.simpleDescription()
    200 print(threeOfSpadesDescription)
    201 
    202 protocol ExampleProtocal {
    203     var simpleDescription: String { get }
    204     func adjust()
    205 }
    206 class SimpleClass: ExampleProtocal {
    207     var simpleDescription: String = "A very simple class."
    208     var anotherProperty: Int = 69105
    209     func adjust() {
    210         simpleDescription += "  Now 100% adjusted."
    211     }
    212 }
    213 var a = SimpleClass()
    214 a.simpleDescription = "fuck"
    215 a.adjust()
    216 print(a.simpleDescription)
    217 
    218 class SimpleClass2: ExampleProtocal {
    219     var simpleDescription: String = "Another very simple class."
    220     func adjust() {
    221         simpleDescription += "  Adjusted."
    222     }
    223 }
    224 var protocolArray: [ExampleProtocal] = [SimpleClass(), SimpleClass(), SimpleClass2()]
    225 for instanse in protocolArray {
    226     instanse.adjust()
    227     print(instanse.simpleDescription)
    228 }
    +V d2h5X251bGw= 请备注:from博客园
  • 相关阅读:
    git warning: LF will be replaced by CRLF in 解决办法
    今天买了个pro,开始ios开发
    基于pyspark的mapreduce实现
    正则表达式中全部符号作用及解释
    CNN
    tensorboard使用及tensorflow各层权重系数输出
    DeepFM tensorflow实现
    FM详解
    sklearn计算auc需要注意的点
    矩阵压缩存储(可用于FM算法中的稀疏矩阵存储)
  • 原文地址:https://www.cnblogs.com/hangj/p/4884123.html
Copyright © 2011-2022 走看看