码迷,mamicode.com
首页 > 编程语言 > 详细

Swift 基本运算符

时间:2015-12-25 18:52:17      阅读:235      评论:0      收藏:0      [点我收藏+]

标签:

// Swift 基本运算符

 

    let a = 4

    var b = 10

    b = a

    print(b)

 

    let (x, y) = (1, 3) // 现在x = 1  y = 3

 

// 加法运算也可用于字符串

 

    let dog:String = "dogs"

    let cow:String = "cows"

    let dogcow = dog + cow

    print(dogcow)

 

 

// 求于

let c: Int = 9

let d: Int = 2

 

let e = c % d

 

print(e)

 

 

// 数值的正负号可以使用前缀-(即一元负号)来切换:

let three = 3

let minusThree = -three       // minusThree 等于 -3

let plusThree = -minusThree   // plusThree 等于 3, "负负3"

 

print(plusThree)

 

 

// 条件运算符 if

 

var name = "hello"

if name == "hello"

{

    print("Hello world")

}

else

{

    print("wrong \(name)")

    

}

 

// 三元条件运算(Ternary Conditional Operator)

/*

  三元条件运算的特殊在于它是有三个操作数的运算符,它的原型是问题?答案1:答案2。它简洁地表达根据问题成立与否作出二选一的操作。如果问题成立,返回答案1的结果; 如果不成立,返回答案2的结果。

*/

 

    let contentheight = 40

    let hasHeight = true

    let rowHeight = contentheight + (hasHeight ? 60 : 20)

    print(rowHeight// rowHeight == 100

 

// 区间运算符 (Swift 提供了两个方便表达一个区间的值的运算符。)

 

for index in 1...5 {

    print("\(index) * 5 = \(index * 5)")

 

}

 

let nameArray = ["jay","Jack","Tom","lucy"]

let count = nameArray.count

 

for i in 0...count

{

//    print("\(i + 1) 个人叫\(nameArray[i])")

//    print("\(nameArray[i])") // 报野指针了

}

 

// 逻辑运算

/*

逻辑运算的操作对象是逻辑布尔值。Swift 支持基于 C 语言的三个标准逻辑运算。

逻辑非(!a

逻辑与(a && b

逻辑或(a || b

逻辑非

 

逻辑非运算(!a)对一个布尔值取反,使得truefalsefalsetrue

 

*/

 

let allowEnpty = false

 

if !allowEnpty {

    print("access")

}

 

// 逻辑与(a && b)表达了只有ab的值都为true时,整个表达式的值才会是true

let enteredDoorCode = true

let passedRetinaScan = false

if enteredDoorCode && passedRetinaScan

{

    print("Welcome!")

}

else

{

    print("ACCESS DENIED")

}

 

// 逻辑或 逻辑或(a || b)是一个由两个连续的|组成的中置运算符。它表示了两个逻辑表达式的其中一个为true,整个表达式就为true

let hasDoorKey = false

let knowsOverridePassword = true

if hasDoorKey || knowsOverridePassword

{

    print("Welcome!")

}

else

{

    print("ACCESS DENIED")

}

// 输出 "Welcome!"

Swift 基本运算符

标签:

原文地址:http://www.cnblogs.com/fantasy3588/p/5076516.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!