学习 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进行开发,苹果发布 ...
随机推荐
- apicloud代码压缩和全局加密
首先说代码压缩,因为没什么用,就先说它了.代码压缩后,apicloud里面的css和js文件里面的空格呀回车呀都去掉了,就是文件小了,所有代码显示为一行了.这些代码的变量没有重命名,我们知道jquer ...
- apicloud管理
以下所有操作都是指“apicloud”平台下的管理: 1. 一定要记得备份证书.证书不是因为你记得别名和密码就能还原的.因为apicloud是服务器session存数据,千万不要打开多个app操作页面 ...
- 2018.06.30 BZOJ3083: 遥远的国度(换根树剖)
3083: 遥远的国度 Time Limit: 10 Sec Memory Limit: 512 MB Description 描述 zcwwzdjn在追杀十分sb的zhx,而zhx逃入了一个遥远的国 ...
- 2018.09.09 UVa10529 - Dumb Bones(期望dp)
传送门 期望dp好题. f[i]表示摆放i个的最小花费,于是f[i]可以从f[j]与f[i-j+1]转移过来了. 代码: #include<bits/stdc++.h> #define N ...
- Linux IPC之共享内存
System V共享内存机制: shmget shmat shmdt shmctl 原理及实现: system V IPC机制下的共享内存本质是一段特殊的内存区域,进程间需要共享的数据被放在该共 ...
- vi 基本使用命令
说明:以下的例子中 xxx 表示在命令模式下输入 xxx 并回车以下的例子中 :xxx 表示在扩展模式下输入 xxx 并回车小括号中的命令表示相关命令在编辑模式或可视模式下输入的命令会另外注明 1 查 ...
- HDU 4355 Party All the Time (三分求极值)
题意:给定x轴上有n个点,每一个点都有一个权值,让在x轴上选一个点,求出各点到这个点的距离的三次方乘以权值最小. 析:首先一开始我根本不会三分,也并没有看出来这是一个三分的题目的,学长说这是一个三分的 ...
- excel绝对引用中间添加符号
=F1&"_"&J1 绝对引用 相对引用 按F4 然后复制全部,选择性黏贴,值和数字即可
- spring mvc 文档哪里有
官方: http://docs.spring.io/spring/docs/4.2.0.RC1/spring-framework-reference/htmlsingle/#spring-web Th ...
- 关于RabbitMQ一点
RabbitMQ是AMQP(高级消息队列协议)的标准实现,理论上可以保证消息发送的准确性 RabbitMQ是用Erlang语言编写的,而Erlang语言具有以下特点: 并发性--Erlang支持超大量 ...