学习 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 比较合适
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 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)的更多相关文章
- ios -- 教你如何轻松学习Swift语法(三) 完结篇
前言:swift语法基础篇(二)来了,想学习swift的朋友可以拿去参考哦,有兴趣可以相互探讨,共同学习哦. 一.自动引用计数 1.自动引用计数工作机制 1.1 swift和o ...
- ios -- 教你如何轻松学习Swift语法(二)
前言:swift语法基础篇(二)来了,想学习swift的朋友可以拿去参考哦,有兴趣可以相互探讨,共同学习哦. 一.可选类型(重点内容) 1.什么是可选类型? 1.1在OC开 ...
- ios -- 教你如何轻松学习Swift语法(一)
目前随着公司开发模式的变更,swift也显得越发重要,相对来说,swift语言更加简洁,严谨.但对于我来说,感觉swift细节的处理很繁琐,可能是还没适应的缘故吧.基本每写一句代码,都要对变量的数据类 ...
- 一步一步学习Swift之(一):关于swift与开发环境配置
一.什么是Swift? 1.Swift 是一种新的编程语言,用于编写 iOS 和 OS X 应用. 2.Swift 结合了 C 和 Objective-C 的优点并且不受 C 兼容性的限制. 3.Sw ...
- 開始学习swift开发
近期要開始学习swift开发了,接下来的日子,会记录学习swift的历程.
- 学习swift语言的快速入门教程推荐
随着苹果产品越来越火爆,苹果新推出的swift必定将在很大程度上代替oc语言.学好swift语言,对于IOS工程师来讲,已经是一门必备技能. 有一些比较好的英文版教程,值得学习. 1. Swift T ...
- 一步一步学习Swift之(二):好玩的工具playground与swfit基础语法
playground好于在于能一边写代码一边看到输出的常量变量的值.不需要运行模拟器. 我们来试一下该工具的用法. 打开xcode6开发工具,选择Get started with a playgrou ...
- 開始学习swift,资料汇总帖
最近開始学习swift,以后mac和ios开发就指望它,曾经学oc半途而废了.主要原因是oc等语法实在能适应,如今有swift了.语法有js,scala,python,c++,oc等语言的影子,又一次 ...
- Swift-如何快速学习Swift
关于本文: 1.说明本文写作的目的 2.整理了Swift的基本语法树 3.看图作文 一.写作目的 昨天看了一个知识专栏,作者讲述的是“如何研究性的学习”.整个课程1个小时9分钟,花了我19块人民币.其 ...
- 学习swift开源项目
如果你是位iOS开发者,或者你正想进入该行业,那么Swift为你提供了一个绝佳的机会.Swift的设计非常优雅,较Obj-C更易于学习,当然也非常强大. 为了指导开发者使用Swift进行开发,苹果发布 ...
随机推荐
- 洛谷 P2986 [USACO10MAR]伟大的奶牛聚集(树形动规)
题目描述 Bessie is planning the annual Great Cow Gathering for cows all across the country and, of cours ...
- 1、HttpClient初探
HttpClient是它的核心接口.可以理解为一个简单的浏览器. 主要方法有: getParams(); 获取运行参数 getConnectionManager(); 获取连接管理器.连接管理器中 ...
- action spring 注入错误,如果检查各项注入都没有错误时,考虑struts 是否配置了namespace(如果你有多个namespace="/")
[ERROR] 2015-01-04 09:42:35,180 (CommonsLogger.java:38) - Exception occurred during processing reque ...
- 关于某一discuz 6.0论坛故障的记录
某日,额突然发现公司的discuz 6.0论坛在IE6浏览器下面显示出现问题: 每个链接都出现了下划线,很难看,不过已访问的链接(a:visted)却没有下划线,于是怀疑css.htm有问题.于是对c ...
- 2018.09.29 bzoj3675: [Apio2014]序列分割(斜率优化dp)
传送门 斜率优化dp经典题目. 首先需要证明只要选择的K个断点是相同的,那么得到的答案也是相同的. 根据分治的思想,我们只需要证明有两个断点时成立,就能推出K个断点时成立. 我们设两个断点分成的三段连 ...
- 2018.09.19 atcoder Snuke's Subway Trip(最短路)
传送门 就是一个另类最短路啊. 利用颜色判断当前节点的最小花费的前驱边中有没有跟当前的边颜色相同的. 如果有这条边费用为0,否则费用为1. 这样跑出来就能ac了. 代码: #include<bi ...
- SecureCRT和乱码
示例: # ls /usr/local/r3c/bin/lib /bin/ls: /usr/local/r3c/bin/lib: ????????? 查看系统字符集设置: # locale LANG= ...
- Object-C 类和对象
//创建对象 //类名 *对象名 = [[类名 alloc] init] /* Car *car = [[Car alloc] init]; //Car ...
- 【转】启动、停止Windows服务的DOS命令
需要用管理员身份运行 在图形界面中启动.停止服务很方便,但是操作系统有时候会出故障,此时不妨使用原始的DOS命令启动.停止服务,也许会收到意想不到的效果的! 方法/步骤 1 开始→所有程序. 2 附件 ...
- 企业计划体系的变迁:从ERP到APS再到SCP
规划是供应链运作的大脑.几十年来,规划从MRP发展到到ERP到APS再到SCP,经历了从部分到全局,从静态到动态,从企业到供应链的发展历程.供应链的效率取决于规划.规划不到位,任何执行都是事后挽救. ...