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.

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

简单说,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/

附上练习代码

 let individualScores = [, , , , ]
var teamScore =
for score in individualScores {
if score > {
teamScore +=
} else {
teamScore +=
}
}
print(teamScore) var optionalName: String? = "John Appleseed"
var greeting = "Hello!"
var optionalHello: String? = "Hello" if let hello = optionalHello where hello.hasPrefix("H"), let name = optionalName {
greeting = "\(hello), \(name)"
}
print(greeting) let vegetable = "red pepper"
var vegetableComment: String?
switch vegetable {
case "celery":
vegetableComment = "Add some raisins and make ants on a log."
case "cucumber", "watercress":
vegetableComment = "That would make a good tea sandwich."
case let x where x.hasSuffix("pepper"):
vegetableComment = "Is it a spicy \(x)?"
default:
vegetableComment = "Everything tastes good in soup."
}
print(vegetableComment) var firstForLoop =
for i in ..< {
firstForLoop += i
}
print(firstForLoop) var secondForLoop =
for _ in ... {
secondForLoop +=
}
print(secondForLoop) func greet(name: String, day: String) -> String {
return "Hello \(name), today is \(day)."
}
print(greet("hangj", day: "Thursday")) let exampleString = "hello"
if exampleString.hasSuffix("lo") {
print("ends in lo")
} var array = ["apple", "banana", "dragonfruit"]
array.insert("cherry", atIndex: )
print(array) class Shape {
var numberOfSides =
func simpleDescription() -> String {
return "A shape with \(numberOfSides) sides."
}
}
var shape = Shape()
shape.numberOfSides =
var shapeDescription = shape.simpleDescription()
print(shapeDescription) class NamedShape {
var numberOfSides =
var name: String init(name: String) {
self.name = name
} func simpleDescription() -> String {
return "A shape with \(numberOfSides) sides."
}
}
let namedShape = NamedShape(name: "my named shape")
print(namedShape.simpleDescription()) class Square: NamedShape {
var sideLength: Double init(sideLength: Double, name: String){
self.sideLength = sideLength
super.init(name: name)
numberOfSides =
} func area() -> Double {
return sideLength * sideLength
} override func simpleDescription() -> String {
return "A suqare with sides of length \(sideLength)."
}
}
let testSquare = Square(sideLength: 5.2, name: "my test square")
print(testSquare.area())
print(testSquare.simpleDescription()) class Circle: NamedShape {
var radius: Double init?(radius: Double, name: String) {
self.radius = radius
super.init(name: name)
numberOfSides =
if radius <= {
return nil
}
} override func simpleDescription() -> String {
return "A circle with a radius of \(radius)."
}
}
if let successfulCircle = Circle(radius: 4.2, name: "successful circle") {
print(successfulCircle.simpleDescription())
}
let failedCircle = Circle(radius: -, name: "failed circle") class Triangle: NamedShape {
init(sideLength: Double, name: String) {
super.init(name: name)
numberOfSides =
}
}
let shapesArray = [Triangle(sideLength: 1.5, name: "triangle1"),
Triangle(sideLength: 4.2, name: "triangle2"), Square(sideLength: 3.2, name: "square1"),
Square(sideLength: 2.7, name: "square2")]
var squares =
var triangles =
for shape in shapesArray {
if let square = shape as? Square {
++squares
} else if let triangle = shape as? Triangle {
++triangles
}
}
print("\(squares) squares and \(triangles) triangles.") enum Rank: Int {
case Ace =
case Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten
case Jack, Queen, King
func simpleDescription() -> String {
switch self {
case .Ace:
return "ace"
case .Jack:
return "jack"
case .Queen:
return "queen"
case .King:
return "king"
default:
return String(self.rawValue)
}
}
}
let ace = Rank.Ace
print(ace.simpleDescription()) enum Suit {
case Spades, Hearts, Diamonds, Clubs
func simpleDescription() -> String {
switch self {
case .Spades:
return "Spades"
case .Hearts:
return "hearts"
case .Diamonds:
return "diamonds"
case .Clubs:
return "clubs"
}
}
}
let hearts = Suit.Hearts
let heartsDescription = hearts.simpleDescription()
print(heartsDescription) struct Card {
var rank: Rank
var suit: Suit
func simpleDescription() -> String {
return "The \(rank.simpleDescription()) of \(suit.simpleDescription())"
}
}
let threeOfSpades = Card(rank: .Three, suit: .Spades)
let threeOfSpadesDescription = threeOfSpades.simpleDescription()
print(threeOfSpadesDescription) protocol ExampleProtocal {
var simpleDescription: String { get }
func adjust()
}
class SimpleClass: ExampleProtocal {
var simpleDescription: String = "A very simple class."
var anotherProperty: Int =
func adjust() {
simpleDescription += " Now 100% adjusted."
}
}
var a = SimpleClass()
a.simpleDescription = "fuck"
a.adjust()
print(a.simpleDescription) class SimpleClass2: ExampleProtocal {
var simpleDescription: String = "Another very simple class."
func adjust() {
simpleDescription += " Adjusted."
}
}
var protocolArray: [ExampleProtocal] = [SimpleClass(), SimpleClass(), SimpleClass2()]
for instanse in protocolArray {
instanse.adjust()
print(instanse.simpleDescription)
}

学习 swift (1)的更多相关文章

  1. ios -- 教你如何轻松学习Swift语法(三) 完结篇

    前言:swift语法基础篇(二)来了,想学习swift的朋友可以拿去参考哦,有兴趣可以相互探讨,共同学习哦.      一.自动引用计数   1.自动引用计数工作机制      1.1 swift和o ...

  2. ios -- 教你如何轻松学习Swift语法(二)

    前言:swift语法基础篇(二)来了,想学习swift的朋友可以拿去参考哦,有兴趣可以相互探讨,共同学习哦.      一.可选类型(重点内容)   1.什么是可选类型?        1.1在OC开 ...

  3. ios -- 教你如何轻松学习Swift语法(一)

    目前随着公司开发模式的变更,swift也显得越发重要,相对来说,swift语言更加简洁,严谨.但对于我来说,感觉swift细节的处理很繁琐,可能是还没适应的缘故吧.基本每写一句代码,都要对变量的数据类 ...

  4. 一步一步学习Swift之(一):关于swift与开发环境配置

    一.什么是Swift? 1.Swift 是一种新的编程语言,用于编写 iOS 和 OS X 应用. 2.Swift 结合了 C 和 Objective-C 的优点并且不受 C 兼容性的限制. 3.Sw ...

  5. 開始学习swift开发

    近期要開始学习swift开发了,接下来的日子,会记录学习swift的历程.

  6. 学习swift语言的快速入门教程推荐

    随着苹果产品越来越火爆,苹果新推出的swift必定将在很大程度上代替oc语言.学好swift语言,对于IOS工程师来讲,已经是一门必备技能. 有一些比较好的英文版教程,值得学习. 1. Swift T ...

  7. 一步一步学习Swift之(二):好玩的工具playground与swfit基础语法

    playground好于在于能一边写代码一边看到输出的常量变量的值.不需要运行模拟器. 我们来试一下该工具的用法. 打开xcode6开发工具,选择Get started with a playgrou ...

  8. 開始学习swift,资料汇总帖

    最近開始学习swift,以后mac和ios开发就指望它,曾经学oc半途而废了.主要原因是oc等语法实在能适应,如今有swift了.语法有js,scala,python,c++,oc等语言的影子,又一次 ...

  9. Swift-如何快速学习Swift

    关于本文: 1.说明本文写作的目的 2.整理了Swift的基本语法树 3.看图作文 一.写作目的 昨天看了一个知识专栏,作者讲述的是“如何研究性的学习”.整个课程1个小时9分钟,花了我19块人民币.其 ...

  10. 学习swift开源项目

    如果你是位iOS开发者,或者你正想进入该行业,那么Swift为你提供了一个绝佳的机会.Swift的设计非常优雅,较Obj-C更易于学习,当然也非常强大. 为了指导开发者使用Swift进行开发,苹果发布 ...

随机推荐

  1. redhat配置java环境

    1.检查是否有旧版本的jdk java -version java version "1.4.2" gij (GNU libgcj) version (Red Hat -) Cop ...

  2. [SoapUI] 在Jenkins上传递project级别的参数给case

  3. JavaScript 的数据类型及其检测

    JavaScript 有几种类型的值? Javascript 有两种数据类型,分别是基本数据类型和引用数据类型.其中基本数据类型包括 Undefined.Null.Boolean.Number.Str ...

  4. 657. Judge Route Circle

    static int wing=[]() { std::ios::sync_with_stdio(false); cin.tie(NULL); ; }(); class Solution { publ ...

  5. 2018.06.29 NOIP模拟 旅馆(线段树)

    旅馆 [问题描述] OIEROIEROIER 们最近的旅游计划,是到长春净月潭,享受那里的湖光山色,以及明 媚的阳光.你作为整个旅游的策划者和负责人,选择在潭边的一家著名的旅馆住 宿.这个巨大的旅馆一 ...

  6. yii框架场景的用法

    1.在 model 里面定义一下场景 类名必须是 scenarios() public function scenarios() { return [ 'create' => ['title', ...

  7. 31. The New Bread Earners 挣钱养家的新军

    31. The New Bread Earners 挣钱养家的新军 ① They call them the new bread earners.They are women,and they are ...

  8. flask_数据库

    我们将使用 Flask-SQLAlchemy扩展来管理我们应用程序的数据.这个扩展封装了SQLAlchemy 项目,这是一个 对象关系映射器 或者 ORM.ORMs 允许数据库应用程序与对象一起工作, ...

  9. 删除重复的feature vba VS 删除重复的feature python

    VBA: Sub deleteDuplicatedFeature() Dim app As IApplication Set app = Application Dim pMxDocument As ...

  10. (最小生成树)Truck History --POJ -- 1789

    链接: http://poj.org/problem?id=1789 Time Limit: 2000MS   Memory Limit: 65536K Total Submissions: 2213 ...