运算符是用来检查,更改或组合值的特殊符号或短语。Swift提供的很多常规的运算符,如+、-、*、/、%、=、==等,以及逻辑运算的&&、||等等,基本上不需要重复介绍,我们在这里只需要了解一些不太一样的运算符就可以了。如Swift引入的新运算符,范围操作符号,包括..<和...两个,该随笔介绍Swift常规的运算符中,以及和其他语言有所差异的部分。

赋值运算符

let b = 10
var a = 5
a = b
// a is now equal to 10

赋值语句,处理和其他语言一样。

let (x, y) = (1, 2)
// x is equal to 1, and y is equal to 2

这种代码是类似ECMAScript 6的脚本写法,通过把右边元祖对象解构赋值给左边对应的参数。

数学运算符

1 + 2       // equals 3
5 - 3 // equals 2
2 * 3 // equals 6
10.0 / 2.5 // equals 4.0

这些都是和其他语言没有什么不同,循例列出参考下

对于字符,也可以使用+符号进行连接新的字符串

"hello, " + "world"  // equals "hello, world"

一元操作符中的-、+运算,和算术里面的负负得正,正负得负的意思一样了。

let three = 3
let minusThree = -three // minusThree equals -3
let plusThree = -minusThree // plusThree equals 3, or "minus minus three"
let minusSix = -6
let alsoMinusSix = +minusSix // alsoMinusSix equals -6

组合运算符提供+= 、-=的运算符操作

var a = 1
a += 2
// a is now equal to 3

对比运算符和其他语言差不多

  • 等于 (a == b)

  • 不等于 (a != b)

  • 大于 (a > b)

  • 小于 (a < b)

  • 大于等于 (a >= b)

  • 小于等于 (a <= b)

另外值得注意的是,Swift提供了对比引用的两个操作符号,=== 和 !==,用来检查两个引用是否完全相等;或者不相等的。而==只是用来对比两个对象的值是否一致。

1 == 1   // true because 1 is equal to 1
2 != 1 // true because 2 is not equal to 1
2 > 1 // true because 2 is greater than 1
1 < 2 // true because 1 is less than 2
1 >= 1 // true because 1 is greater than or equal to 1
2 <= 1 // false because 2 is not less than or equal to 1

对比运算符也经常用来If条件语句里面

let name = "world"
if name == "world" {
print("hello, world")
} else {
print("I'm sorry \(name), but I don't recognize you")
}
// Prints "hello, world", because name is indeed equal to "world".

三元运算符

三元运算符 ? :和C#里面表现是一样的

question ? answer1 : answer2
let contentHeight = 40
let hasHeader = true
let rowHeight = contentHeight + (hasHeader ? 50 : 20)

空值转换操作符

空值转换符是对可空类型(可选类型)的一个值得转换出来(a ?? b)。

let defaultColorName = "red"
var userDefinedColorName: String? // defaults to nil var colorNameToUse = userDefinedColorName ?? defaultColorName
// userDefinedColorName is nil, so colorNameToUse is set to the default of "red"
userDefinedColorName = "green"
colorNameToUse = userDefinedColorName ?? defaultColorName
// userDefinedColorName is not nil, so colorNameToUse is set to "green"

范围操作符

闭合范围运算符 ... 和半闭合范围运算符 ..< 两个

for index in 1...5 {
print("\(index) times 5 is \(index * 5)")
}
// 1 times 5 is 5
// 2 times 5 is 10
// 3 times 5 is 15
// 4 times 5 is 20
// 5 times 5 is 25

半闭合的范围运算符

let names = ["Anna", "Alex", "Brian", "Jack"]
let count = names.count
for i in 0..<count {
print("Person \(i + 1) is called \(names[i])")
}
// Person 1 is called Anna
// Person 2 is called Alex
// Person 3 is called Brian
// Person 4 is called Jack

或者如下使用

for name in names[..<2] {
print(name)
}
// Anna
// Alex

以及一侧范围的运算符,包括左侧和右侧两个部分

for name in names[2...] {
print(name)
}
// Brian
// Jack for name in names[...2] {
print(name)
}
// Anna
// Alex
// Brian
let range = ...5
range.contains(7) // false
range.contains(4) // true
range.contains(-1) // true

逻辑运算符

let allowedEntry = false
if !allowedEntry {
print("ACCESS DENIED")
}
// Prints "ACCESS DENIED"
let enteredDoorCode = true
let passedRetinaScan = false
if enteredDoorCode && passedRetinaScan {
print("Welcome!")
} else {
print("ACCESS DENIED")
}
// Prints "ACCESS DENIED"
let hasDoorKey = false
let knowsOverridePassword = true
if hasDoorKey || knowsOverridePassword {
print("Welcome!")
} else {
print("ACCESS DENIED")
}
// Prints "Welcome!"
if enteredDoorCode && passedRetinaScan || hasDoorKey || knowsOverridePassword {
print("Welcome!")
} else {
print("ACCESS DENIED")
}
// Prints "Welcome!"

或者使用括号使之更加方便阅读

if (enteredDoorCode && passedRetinaScan) || hasDoorKey || knowsOverridePassword {
print("Welcome!")
} else {
print("ACCESS DENIED")
}
// Prints "Welcome!"

快看Sample代码,速学Swift语言(3)-运算符的更多相关文章

  1. 快看Sample代码,速学Swift语言(1)-语法速览

    Swift是苹果推出的一个比较新的语言,它除了借鉴语言如C#.Java等内容外,好像还采用了很多JavaScript脚本里面的一些脚本语法,用起来感觉非常棒,作为一个使用C#多年的技术控,对这种比较超 ...

  2. 快看Sample代码,速学Swift语言(2)-基础介绍 快看Sample代码,速学Swift语言(1)-语法速览

    快看Sample代码,速学Swift语言(2)-基础介绍 Swift语言是一个新的编程语言,用于iOS, macOS, watchOS, 和 tvOS的开发,不过Swift很多部分内容,我们可以从C或 ...

  3. 快看Sample代码,速学Swift语言(2)-基础介绍

    Swift语言是一个新的编程语言,用于iOS, macOS, watchOS, 和 tvOS的开发,不过Swift很多部分内容,我们可以从C或者Objective-C的开发经验获得一种熟悉感.Swif ...

  4. 重学C语言---05运算符、表达式和语句

    一.循环简介 实例程序 /*shoes1.c--把一双鞋的尺码变为英寸*/#include <stdio.h>#define ADJUST 7.64#define SCALE 0.325 ...

  5. Swift语言 1小时速学教程

    本文由 张渊杰 (网名寂静)编写 Swift语言 1小时速学教程 写在前面的话 有些人可能想, 呵呵, 1小时学一门语言, 你不是搞笑吧, 我想说, 是的, 完全可以, 就要看你怎么学了 要想在1小时 ...

  6. 边看MHA源码边学Perl语言之一开篇

    边看MHA源码边学Perl语言之一开篇 自我简介 先简单介绍一下自己,到目前为此我已经做了7年左右的JAVA和3年左右php开发与管理,做java时主要开发物流行业的相关软件,对台湾快递,国际快递,国 ...

  7. 基于Swift语言开发微信、QQ和微博的SSO授权登录代码分析

    前言 Swift 语言,怎么说呢,有一种先接受后排斥.又欢迎的感觉,纵观国外大牛开源框架或项目演示,Swift差点儿占领了多半,而国内尽管出现非常多相关技术介绍和教程,可是在真正项目开发中使用的占领非 ...

  8. Swift语言 简明基础 代码演示样例

    开发环境: Mac.Xcode6.0 下面内容均可创建ios common line项目来測试 1.Hello World演示样例 使用xcode创建新的common line项目,查看主文件main ...

  9. 《从零开始学Swift》学习笔记(Day 69)——Swift与Objective-C混合编程之语言

    原创文章,欢迎转载.转载请注明:关东升的博客 在Swift语言出现之前,开发iOS或OS X应用主要使用Objective-C语言,此外还可以使用C和C++语言,但是UI部分只能使用Objective ...

随机推荐

  1. windows网络编程中文 笔记(一)

    OSI网络模型 OSI(Open System Interconnection)开放系统互联 第七层 应用层 为用户提供相应的界面,以便使用提供的连网功能 第六层 表示层 完成数据的格式化 第五层 会 ...

  2. 省市区三级联动(附j全国省市区json文件)

    效果如图所示: 首先提供全国所有省份的JS文件 下载地址:https://files.cnblogs.com/files/likui-bookHouse/address.rar 打开js内容如下: h ...

  3. C#面向对象 类的封装

    class student { public int _code; public int Code//属性 { //获取值 get { ; } //设置值 set { _code = value + ...

  4. PostgreSQL 表值函数

    方法1create type deptSon as ( mid ), id ), name ), DeptParentId ) ); CREATE OR REPLACE FUNCTION functi ...

  5. HttpHandler实现网页图片防盗链

    using System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary ...

  6. {windows故障}关于WIN7故障模块StackHash_0a9e解决方法

    问题背景:我给同事重装好系统后,想用驱动精灵(网卡版)给新系统安装驱动,但是在安装驱动精灵的过程中老是出现标题的问题,windows停止工作,导致无法安装,最后看到这两个方法后,把网络适配器禁用,然后 ...

  7. 15个实用的PHP正则表达式

    对于开发人员来说,正则表达式是一个非常有用的功能,它提供了 查找,匹配,替换 句子,单词,或者其他格式的字符串.这篇文章主要介绍了15个超实用的php正则表达式,需要的朋友可以参考下.在这篇文章里,我 ...

  8. mysql统计一年12月的数据

    效果图: select end) as 一月份, end) as 二月份, end) as 三月份, end) as 四月份, end) as 五月份, end) as 六月份, end) as 七月 ...

  9. Java学习笔记--Cglib动态代理

    CGLib动态代理 使用JDK创建代理有一个限制,即它只能为接口创建代理实例,这一点可以从Proxy的接口方法newProxyInstance(ClassLoader loader,Class[] i ...

  10. 第一次使用Open Live Writer维护BlogJava

    换了电脑,又重装了一堆东西,现在才把Open Live Writer整好.顺便记下几个心得: Open Live Writer已经没办法从网站上下载了,介绍个方法,可以把地址直接拷贝到迅雷里面,然后请 ...