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. 改变父元素的透明度,不影响子元素的透明度—css

    1.如果我们给父元素添加opacity:0.4后,子元素的red颜色也变成了0.4的透明度, 例子如下: <!DOCTYPE html> <html> <head> ...

  2. 从输入url到显示网页发生了什么

    原文链接:https://juejin.im/post/5bf23afa6fb9a049be5d1494 在浏览器中输入url到显示网页主要包含两个部分: 网络通信和页面渲染 互联网内各网络设备间的通 ...

  3. li.active2有加强重要性的效果。

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...

  4. scrapy官方安装方法

    安装依赖 sudo apt-get install python-dev python-pip libxml2-dev libxslt1-dev zlib1g-dev libffi-dev libss ...

  5. 纯css手写圆角气泡对话框 微信小程序和web都适用

    嗯……我们设计师强烈要求一定要圆角!圆角的气泡对话框,不要那种尖角的.这其中还遇上了个尴尬的问题,z-index不生效 无非就是两种方法,一种是使用图片再定位拼接起来使用,太简单了具体就不详细的说了. ...

  6. Jigloo 下载 安装 GUI

    这个需要授权,一直不能解决!! 网上找了很多,都觉不能访问,这个可以用Eclipse直接更新的 http://www.cloudgardensoftware.com/jigloo/update-sit ...

  7. 2081.09.22 Kuma(非旋treap)

    描述 有N张卡片,编号从0到n-1, 刚开始从0到n-1按顺序排好. 现有一个操作, 对于p. l,表示从第p张卡片之后的l张卡片拿到 最前面. 例如n=7的时候, 刚开始卡片序列为0 1 2 3 4 ...

  8. angularjs写公共方法

    'use strict'; angular.module('fast-westone') .factory('commonUtilService', function () { return { /* ...

  9. html转jsp部分css不可用

    解决方法 <%String path = request.getContextPath();String basePath = request.getScheme()+"://&quo ...

  10. 201709011工作日记--Volley源码详解(三)

    1. RequestQueue类 我们使用 Volley 的时候创建一个 request 然后把它丢到 RequestQueue 中就可以了.那么来看 RequestQueue 的构造方法,含有四个参 ...