从今天开始学习Swift -- Swift 初见 (转)
原文地址:http://www.cocoachina.com/newbie/basic/2014/0604/8675.html
println("hello, world")
注意:为了获得最好的体验,在 Xcode 当中使用代码预览功能。代码预览功能可以让你编辑代码并实时看到运行结果。 |
var myVariable =
myVariable =
let myConstant =
let implicitInteger =
let implicitDouble = 70.0
let explicitDouble: Double =
let label = "The width is"
let width =
let widthLabel = label + String(width)
let apples =
let oranges =
let appleSummary = "I have \(apples) apples."
let fruitSummary = "I have \(apples + oranges) pieces of fruit."
var shoppingList = ["catfish", "water", "tulips", "blue paint"]
shoppingList[] = "bottle of water" var occupations = [
"Malcolm": "Captain",
"Kaylee": "Mechanic",
]
occupations["Jayne"] = "Public Relations"
let emptyArray = String[]()
let emptyDictionary = Dictionary<String, Float>()
shoppingList = [] // 去逛街并买点东西
let individualScores = [, , , , ]
var teamScore =
for score in individualScores {
if score > {
teamScore +=
} else {
teamScore +=
}
}
teamScore
var optionalString: String? = "Hello"
optionalString == nil var optionalName: String? = "John Appleseed"
var greeting = "Hello!"
if let name = optionalName {
greeting = "Hello, \(name)"
}
let vegetable = "red pepper"
switch vegetable {
case "celery":
let vegetableComment = "Add some raisins and make ants on a log."
case "cucumber", "watercress":
let vegetableComment = "That would make a good tea sandwich."
case let x where x.hasSuffix("pepper"):
let vegetableComment = "Is it a spicy \(x)?"
default:
let vegetableComment = "Everything tastes good in soup."
}
let interestingNumbers = [
"Prime": [, , , , , ],
"Fibonacci": [, , , , , ],
"Square": [, , , , ],
]
var largest =
for (kind, numbers) in interestingNumbers {
for number in numbers {
if number > largest {
largest = number
}
}
}
largest
var n =
while n < {
n = n *
}
n var m =
do {
m = m *
} while m <
m
- var firstForLoop = 0
for i in .. {
firstForLoop += i
}
firstForLoop var secondForLoop =
for var i = ; i < ; ++i {
secondForLoop +=
}
secondForLoop
func greet(name: String, day: String) -> String {
return "Hello \(name), today is \(day)."
}
greet("Bob", "Tuesday")
func getGasPrices() -> (Double, Double, Double) {
return (3.59, 3.69, 3.79)
}
getGasPrices()
func sumOf(numbers: Int...) -> Int {
var sum =
for number in numbers {
sum += number
}
return sum
}
sumOf()
sumOf(, , )
func returnFifteen() -> Int {
var y =
func add() {
y +=
}
add()
return y
}
returnFifteen()
func makeIncrementer() -> (Int -> Int) {
func addOne(number: Int) -> Int {
return + number
}
return addOne
}
var increment = makeIncrementer()
increment()
func hasAnyMatches(list: Int[], condition: Int -> Bool) -> Bool {
for item in list {
if condition(item) {
return true
}
}
return false
}
func lessThanTen(number: Int) -> Bool {
return number <
}
var numbers = [, , , ]
hasAnyMatches(numbers, lessThanTen)
numbers.map({
(number: Int) -> Int in
let result = * number
return result
})
sort([, , , , ]) { $ > $ }
class Shape {
var numberOfSides =
func simpleDescription() -> String {
return "A shape with \(numberOfSides) sides."
}
}
var shape = Shape()
shape.numberOfSides =
var shapeDescription = shape.simpleDescription()
class NamedShape {
var numberOfSides: Int =
var name: String init(name: String) {
self.name = name
} func simpleDescription() -> String {
return "A shape with \(numberOfSides) sides."
}
}
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 square with sides of length \(sideLength)."
}
}
let test = Square(sideLength: 5.2, name: "my test square")
test.area()
test.simpleDescription()
class EquilateralTriangle: NamedShape {
var sideLength: Double = 0.0 init(sideLength: Double, name: String) {
self.sideLength = sideLength
super.init(name: name)
numberOfSides =
} var perimeter: Double {
get {
return 3.0 * sideLength
}
set {
sideLength = newValue / 3.0
}
} override func simpleDescription() -> String {
return "An equilateral triagle with sides of length \(sideLength)."
}
}
var triangle = EquilateralTriangle(sideLength: 3.1, name: "a triangle")
triangle.perimeter
triangle.perimeter = 9.9
triangle.sideLength
class TriangleAndSquare {
var triangle: EquilateralTriangle {
willSet {
square.sideLength = newValue.sideLength
}
}
var square: Square {
willSet {
triangle.sideLength = newValue.sideLength
}
}
init(size: Double, name: String) {
square = Square(sideLength: size, name: name)
triangle = EquilateralTriangle(sideLength: size, name: name)
}
}
var triangleAndSquare = TriangleAndSquare(size: , name: "another test shape")
triangleAndSquare.square.sideLength
triangleAndSquare.triangle.sideLength
triangleAndSquare.square = Square(sideLength: , name: "larger square")
triangleAndSquare.triangle.sideLength
class Counter {
var count: Int =
func incrementBy(amount: Int, numberOfTimes times: Int) {
count += amount * times
}
}
var counter = Counter()
counter.incrementBy(, numberOfTimes: )
let optionalSquare: Square? = Square(sideLength: 2.5, name: "optional square")
let sideLength = optionalSquare?.sideLength
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.toRaw())
}
}
}
let ace = Rank.Ace
let aceRawValue = ace.toRaw()
if let convertedRank = Rank.fromRaw() {
let threeDescription = convertedRank.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()
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()
enum ServerResponse {
case Result(String, String)
case Error(String)
} let success = ServerResponse.Result("6:00 am", "8:09 pm")
let failure = ServerResponse.Error("Out of cheese.") switch success {
case let .Result(sunrise, sunset):
let serverResponse = "Sunrise is at \(sunrise) and sunset is at \(sunset)."
case let .Error(error):
let serverResponse = "Failure... \(error)"
}
protocol ExampleProtocol {
var simpleDescription: String { get }
mutating func adjust()
}
class SimpleClass: ExampleProtocol {
var simpleDescription: String = "A very simple class."
var anotherProperty: Int =
func adjust() {
simpleDescription += " Now 100% adjusted."
}
}
var a = SimpleClass()
a.adjust()
let aDescription = a.simpleDescription struct SimpleStructure: ExampleProtocol {
var simpleDescription: String = "A simple structure"
mutating func adjust() {
simpleDescription += " (adjusted)"
}
}
var b = SimpleStructure()
b.adjust()
let bDescription = b.simpleDescription
extension Int: ExampleProtocol {
var simpleDescription: String {
return "The number \(self)"
}
mutating func adjust() {
self +=
}
} .simpleDescription
let protocolValue: ExampleProtocol = a
protocolValue.simpleDescription
// protocolValue.anotherProperty // Uncomment to see the error
func repeat<ItemType>(item: ItemType, times: Int) -> ItemType[] {
var result = ItemType[]()
for i in ..times {
result += item
}
return result
}
repeat("knock", )
// Reimplement the Swift standard library's optional type
enum OptionalValue<T> {
case None
case Some(T)
}
var possibleInteger: OptionalValue<Int> = .None
possibleInteger = .Some()
func anyCommonElements <T, U where T: Sequence, U: Sequence, T.GeneratorType.Element: Equatable, T.GeneratorType.Element == U.GeneratorType.Element> (lhs: T, rhs: U) -> Bool {
for lhsItem in lhs {
for rhsItem in rhs {
if lhsItem == rhsItem {
return true
}
}
}
return false
}
anyCommonElements([, , ], [])
从今天开始学习Swift -- Swift 初见 (转)的更多相关文章
- Swift语法初见
Swift语法初见 http://c.biancheng.net/cpp/html/2424.html 类型的声明: let implicitInteger = 70 let implicitDoub ...
- ios swift学习日记1-Swift 初见
最近ios的swift语言似乎火了,我没有objectc基金会,但在此之前有cjava的基础的.从这几天開始学习ios的swift语言.后期以博客形式公布.这里提供一本翻译的英文版的swif书籍. 还 ...
- 【Swift学习】Swift编程之旅(三)
元组(tuples) tuples是将多个单一的值组合为一个复合的值.它可以包含任何类型的值,而不需要都是相同类型. 一.元组的创建 1. let http404error = (,"NOT ...
- 【Swift学习】Swift编程之旅(一)
学习一门新语言最经典的例子就是输出“Hello World!” print("Hello World!") swift就是这样来输出的. 如果你使用过其他语言,那么看上去是非常的熟 ...
- Swift 学习Using Swift mix and match, network: 写rss读者
有使用第三方库.因此,需要使用mix and match财产. 请指出错误,谢谢! rss 阅读器,非常easy的代码.仅仅是为了学习swift语言而写. 1、BaseViewController.s ...
- swift swift学习笔记--函数和闭包
使用 func来声明一个函数.通过在名字之后在圆括号内添加一系列参数来调用这个方法.使用 ->来分隔形式参数名字类型和函数返回的类型 func greet(person: String, day ...
- Swift 学习 用 swift 调用 oc
开发过程中 很可能 把swift不成熟的地方用成熟的oc 代码来弥补一下 , 下面简单来学习一下,我也是照着视频 学习的 卖弄谈不上 就是一次学习笔记, 具体问题还是具体分析吧. 需求 给展出出来的 ...
- 【Swift学习】Swift编程之旅---可选链(二十一)
可选链Optional Chaining是一种可以在当前值可能为nil的可选值上请求和调用属性.方法及下标的方法.如果可选值有值,那么调用就会成功:如果可选值是nil,那么调用将返回nil.多个调用可 ...
- 【Swift学习】Swift编程之旅---ARC(二十)
Swift使用自动引用计数(ARC)来跟踪并管理应用使用的内存.大部分情况下,这意味着在Swift语言中,内存管理"仍然工作",不需要自己去考虑内存管理的事情.当实例不再被使用时, ...
随机推荐
- 【转】ClickOnce部署Winform程序的方方面面
源地址:http://www.cnblogs.com/parry/archive/2012/10/30/ClickOnce_Winform_Deployment.html
- hyperledger fabric 中java chaincode 支持离线打包
联盟链由于其本身的特性,目前应用在一些大型国有企业银行比较多.出于安全考虑,这些企业一般会隔离外网环境.所以在实际生产需求中可能存在需要在一个离线的环境中打包安装chaincode的情况. 本文基于这 ...
- 智能合约安全事故回顾(2)-BEC溢出攻击
讲溢出攻击之前,先给大家讲个故事:2014年的时候,美国的宾夕法尼亚州的某个小镇上发生了一个乌龙事件,征兵系统对一万多名1893年到1897出生的男子发去信函,要求他们注册参军,否则面临罚款和监禁.收 ...
- .NET 反射
反射是.NET很强大的一个机制. 它就像照妖镜一般的存在.它能调用你的任意私有成员,如:私有构造函数.私有方法.私有字段. 类的构造函数声明为了private,别人无法实例化对象出来?No,No,No ...
- ios中的奇怪崩溃Signal和EXC_BAD_ACCESS错误分析
什么是Signal 在计算机科学中,信号(英语:Signals)是Unix.类Unix以及其他POSIX兼容的操作系统中进程间通讯的一种有限制的方式.它是一种异步的通知机制,用来提醒进程一个事件已经发 ...
- mysql 字段类型VARCHAR转换成DECIMAL
在我们写代码的实际业务中,有时候实体类用的是String,数据库中自然是VARCHAR类型,但是如果这个实体的属性值放的是数字类型,你查询的时候又需要对它进行排序.sql怎么写呢. 别担心mysql提 ...
- LUNA16数据集(三)预处理
在(一)和(二)中简单介绍了LUNA16数据集的组成,以及肺结节的可视化,有了对数据集的基本了解后,还要对数据集进行预处理,计算机视觉中原始数据一般不会直接送入神经网络,这里也是如此. 这篇博客想写已 ...
- POJ1053 Set Me
题目来源:http://poj.org/problem?id=1053 题目大意: 有一种牌,共有81张.每张牌有四个属性,每种属性有三种可能取值:形状(D,O,S),数字(1,2,3),颜色(R,G ...
- Java使用Array类创建多维数组
1.创建一维数组 import java.lang.reflect.Array; public class ArrayTest { public static void main(String[] a ...
- day_05 字典
1. 字典 1.成对保存数据 ,以key:value形式保存 2.以{}表示,每项内容都是key:value,元素之间用逗号隔开 3.key是不可重复的 4.字典以hash算法来计算key的hash值 ...