从今天开始学习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语言中,内存管理"仍然工作",不需要自己去考虑内存管理的事情.当实例不再被使用时, ...
随机推荐
- [SinGuLaRiTy] 2017-07-21 综合性测试
[SinGuLaRiTy-1028] Copyright (c) SinGuLaRiTy 2017. All Rights Reserved. 对于所有题目:Time Limit: 1s | Memo ...
- 51nod1455(dp)
题目链接: http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1455 题意: 中文题诶~ 思路: dp 1 <= n, ...
- SpringBoot Junit测试Controller
原文链接:https://blog.csdn.net/xiaolyuh123/article/details/73281522 import java.util.List; import org.sp ...
- P4345 [SHOI2015]超能粒子炮·改 Lucas
\(\color{#0066ff}{ 题目描述 }\) 曾经发明了脑洞治疗仪与超能粒子炮的发明家 SHTSC 又公开了他的新发明:超能粒子炮・改--一种可以发射威力更加强大的粒子流的神秘装置. 超能粒 ...
- MPI环境配置
单机多核配置:https://www.cnblogs.com/shixiangwan/p/6626156.html 多计算机配置:https://blog.csdn.net/WASEFADG/arti ...
- P5019 铺设道路 (NOIP2018)
传送门 NOIP2013原题 貌似官方数据都是一模一样的 以前写过竟然毫无印象? 考场上自己瞎JB推结论 显然,如果连续的两端区间可以左边区间减 k 次,右边区间也减 k 次 那么把两个区间合并起来一 ...
- 1972 HH的项链
传送门 主席树解法设las[ i ]表示数列中第 i 个数的值 上一次出现的位置,num[ i ]为原数列中第 i 个数的值1. 把 从第 1 到第 i 个数的 las 的值 的出现次数 建立一个线 ...
- day19 MRO C3算法 super()
1. MRO(Method Resolution Order):方法解析顺序,主要用于在多继承时判断调的属性的路径(来自于哪个类). 1.Python语言包含了很多优秀的特性,其中多重继承就是其中之一 ...
- redis安装及应用
Redis安装及主从配置 server2,3,4. 安装 tar zxf redis-4.0.1.tar.gz cd redis-4.0.1 yum install -y gcc make make ...
- ZPL JS 调用共享打印机
<script type="text/javascript"> function printZpl(zpl) {var printWindow = window.ope ...