Swift 基本数据类型与运算符表达式

//

//  main.swift

//  LessonSwift01

//

//  Created by lanouhn on 16/1/25.

//  Copyright © 2016年 齐彦坤. All rights reserved.

//

 

import Foundation

// 输出函数

print("Hello, World!")

 

// 单行注释 //

// 块注释 

/*

/*

   可以嵌套注释

*/

*/

// 程序运行期间值不会改变得量叫着常量

// 定义一个常量 用let修饰

// let 常量名: 类型 = 值

// 定义一个int类型的常量

// 变量常量命名规则: 数字, 字母, 下划线, 大部分的特殊字符, Unicode字符都可以, 但是非法的Unicode字符, 数字符号, 表制符不可以

/*

let 常量: Int = 10

let ?: String = "高兴"

let 字符:Character = "a"

print(常量, 字符)

// swift当中我们不需要再语句结束时以分号结尾, 但是如果一行中写了几个语句, 他们之间需要用分号隔开

 

let a: Int = 10; let b: Float = 10.5

// 常量 = 20

 

// 变量

// 程序运行期间值可以被改变的量

 

// 定义变量

// var 变量名: 类型 = 值

// Int在不同的操作系统下所占得字节数不同, 64为操作系统下 64 / 8 个字节, 32为操作系统下 32 / 8 个字节

//var 变量: Int = 10

var 变量 = 20

变量 = 50

print(变量)

 

// 类型推断

// 在Swift当中, 系统会根据我们给常量或者变量赋的值来确定常量或则变量点的类型

let aNumber = 20 // 根据推断, aNumber 为Int类型

var aString = "hello, world" // 根据类型推断, aString为String类型

 

//  aString = 10

var aFloatNumber = 20.0 // double 类型

aFloatNumber = 30 // double

 

print(aFloatNumber)

 

let aIntNumber = 30

 

// Swift 是一门类型安全的语言, 不能给一个类型点的变量符另一种类型的值

// aFloatNumber = aIntNumber  类型不匹配

 

let ab: Int = 19

let ac: Float = 20.5

// 不同类型不能相加减

let ad = Float(ab) + ac // 类型转换 类型名 (要转换的变量或则常量名)

print(ad)

 

// 数值字面量

// 二进制字面量

// 以0b开头

let 二进制 = 0b1001

print(二进制)

 

// 8进制 以0o开头

let 八进制 = 0o17

print(八进制)

 

// 十进制

let 十进制 = 10

print(十进制)

 

// 十六进制

// 以0x开头

let 十六进制 = 0x1F

print(十六进制)

// 字符串插值, Swift当中没有占位符, 我们可以用字符串插值的形式当做占位符 \()

var aStr = "hello"

print("aStr = \(aStr)")

// 打印执行最大值, 最小值

print(Int8.max); print(INT8_MAX)

print(Int8.min); print(INT8_MIN)

 

// 类型别名的使用

typealias int_number_long_waige = Int8

print(int_number_long_waige.max)

print(int_number_long_waige.min)

 

// 布尔类型, 只有true 和 false

var 布尔值: Bool = true

print(布尔值)

 

// 元组

// Swift提供的一个高阶类型, 多个不同类型的值组成的复合值

var aTurple = ("小明", 18, "男", 98.5)

// 取出元组里面的成员, 通过元祖名.下标

print(aTurple.0, aTurple.1)

// 在定义元组的时候, 如果元组成员变量前面有名字, 我们也可以通过 元组名.成员名 的方式取值

var 元组 = (姓名: "小强", 年龄: 20, 分数:100.0)

print(元组.姓名, 元组.1)

 

// 元组的分解

let (name, 年龄, 分数) = 元组

print(name)

 

// 可选类型

// 用来处理值缺失的情况, var 名字: 类型?

var abc: Int?

abc = nil // 不加 ? 不能置为nil

abc = 20

print(abc ?? 0)

// 我们要想使用可选类型变量的值, 需要在可选类型变量后面加一个 ! 来解析可选类型变量的值 ,这种方式叫做强制解析

// 强制解析的对象必须赋值

let result = abc! + 15

print(result)

 

//var aNumberOfFloat: Float?

// print(aNumberOfFloat!) // 强制解析可选类型变量之前, 我们要确保可选类型变量已有值, 不能为空

 

// 隐式解析类型 --> 强制解析, 无可选类型, 以后定义是直接定义这种类型, 不可选类型

var 隐式解析类型: Int!

隐式解析类型 = 10

隐式解析类型 = nil

// 使用隐式解析类型的时候一定要确保他有值, 置为nil之后不再用就是, 不会crash

print(隐式解析类型)

 

// 断言

// 起到断点调试的作用

var aNumberOfOptional: Int?

aNumberOfOptional = 19

//aNumberOfOptional = nil

// aNumberOfOptional != nil 将不会crash, 若为空, message --> 可选类型为空, 在此处crash

assert(aNumberOfOptional != nil, "可选类型为空")

print(aNumberOfOptional!)

 

*/

 

 

// 算术运算符

// 按照操作数的不同, 运算符可以分为一元/ 二元/ 三元

// + - * / %

var a = 5

let b = 3

var c = a + b

print("c = \(c)")

 

c = a - b

print("c = \(c)")

 

c = a * b

print("c = \(c)")

 

c = a / b

print("c = \(c)")

 

c = a % b

print("c = \(c)")

 

// 符合赋值运算符

// +=, -=, *=, /=, %=

var d = 10

var e = 11

d += e

print("d = \(d)")

d -= e

print("d = \(d)")

d *= e

print("d = \(d)")

d /= e

print("d = \(d)")

d %= e

print("d = \(d)")

 

// 三木运算符 Bool ? 值1 : 值2, 条件为真, 取值1, 条件为假, 取值2

let number1 = 10

let number2 = 20

let maxValue = number1 > number2 ? number1 : number2

print("maxValue = \(maxValue)")

 

// 等价于

if number1 > number2 {

    let result = number1

    print(result)

}else {

    let result = number2

    print(result)

}

 

// 比较运算符

// > >= < <= == != (=== !==), 比较运算符都有返回值(Bool)

// Swift当中的赋值运算符没有返回值, 不能作为if判断条件

/* error

var aNumber = 10

if aNumber = 12 {

    print("aNumber = \(aNumber)")

}

*/

var x = 5

var y = 10

if x > y {

    print("\(x) > \(y)")

}

if x < y {

    print("x 比 y小")

}

if x >= y {

   print("x 不比 y 小")

}

if x <= y {

   print("x 不比 y 大")

}

if x != y {

    print("x 和 y 不相等")

}

if x == y {

    print("x 和 y 相等")

}

 

// 空合运算符 ??

// 1. 空合运算符, 左边必须是可选类型

// 2. 运算符左右两边的类型必须一致

// 作用: 判断运算符左边的可选类型是否有值, 如果可选类型有值, 就取可选类型的值, 如果无, 就取右边的值

var optionalValue: Int? = 10

var intValue: Int = 20

let result = optionalValue ?? intValue

print("result = \(result)")

 

// 等价于

let result2 = optionalValue != nil ? optionalValue : intValue

print("result2 = \(String(describing: result2))")

 

// 自增, 自减运算符

// 技巧 ++(--)在前去新值, ++(--)在后取旧值

// 第一个警告:++ 和 --将要在Swift3中废弃;可以使用 += 1替代; 

// 参考链接

// http://www.jianshu.com/p/e9b502f5101f

// http://swift.gg/2016/03/30/swift-qa-2016-03-30/ 

 

/*

Official statement:

    1. These operators increase the burden to learn Swift as a first programming language - or any other case where you don't already know these operators from a different language.

    2. Their expressive advantage is minimal - x++ is not much shorter than x += 1.

    3. Swift already deviates from C in that the =, += and other assignment-like operations returns Void (for a number of reasons). These operators are inconsistent with that model.

    4. Swift has powerful features that eliminate many of the common reasons you'd use ++i in a C-style for loop in other languages, so these are relatively infrequently used in well-written Swift code. These features include the for-in loop, ranges, enumerate, map, etc.

    5. Code that actually uses the result value of these operators is often confusing and subtle to a reader/maintainer of code. They encourage "overly tricky" code which may be cute, but difficult to understand.

    6. While Swift has well defined order of evaluation, any code that depended on it (like foo(++a, a++)) would be undesirable even if it was well-defined.

    7. These operators are applicable to relatively few types: integer and floating point scalars, and iterator-like concepts. They do not apply to complex numbers, matrices, etc.

    Finally, these fail the metric of "if we didn't already have these, would we add them to Swift 3?"

 

 */

 

var a_1 = 9

    a_1 += 1

let  result_1 = a_1   // 20

print("result_1 = \(result_1)")

 

// 逻辑运算符

// 逻辑与(&&), 逻辑或(||), 逻辑非(!)

// 注意短路现象, 逻辑与一假即假, 如果运算符前段的条件为假, 运算符后面的就不会走; 逻辑或, 一真即真, 如果运算符前面的条件为真, 那么后面的条件就不会走; 逻辑非, 非假即真

// 逻辑与(&), 逻辑或(|), 不短路, 作用与 "&& ||" 相同

// ^ 异或两者不相同则返回 true, 相同则为 flase

 

var a__1 = 12

a__1 += 1

if a__1 == 12 && a__1  < 13{

    print(a__1)

}

print(-a__1)

 

if a__1 == 12 || a__1 > 13 {

    print(a__1)

    

}

print(a__1)

 

if !(a__1 == 14) {

    print(a__1)

}

 

 

// 字符串

// Swift当中, 字符串没有可变与不可变之分 ,要想修改字符串的值我们只需要用 var 来修饰, 如果不想改变字符串的值, 我们用let来修饰

var aString: String = "123"

// 字符串转Int

var anotherStrirng = Int(aString) //optional(123) 类型

// 强制解析

if anotherStrirng != nil {

    print(anotherStrirng!) // 123

}else {

    print("aString 不能转化为Int类型")

}

// as 转类型

var aNSStringVlue = aString as NSString

print(aNSStringVlue.length)

// 定义OC的字符串

var str1: NSString = "hello, world"

print(str1.length)

 

var aStr = "meinv.png"

if aStr.hasPrefix("meinv") {

    print("有前缀mneinv")

}

// 判断字符串是否有后缀

if aStr.hasSuffix(".png") {

    print("有后缀.png")

}

// 遍历字符串中的字符

for 字符 in aStr.characters {

    print(字符)

}

 

// 判断字符串是否为空

if aStr.isEmpty {

    print("字符串为空")

}else {

    print("字符串不为空")

}

 

let 大写字符串 = aStr.uppercased()

print(大写字符串)

let 小写字符串 = aStr.lowercased()

print(小写字符串)

 

// 数组

// 创建空数组的方式

var emptyArray: Array<String> = Array() // init方法

var emptyArray2: [Int] = Array()

var emptyArray3 = [String]()

// OC中的数组

var arrayOfOC = NSMutableArray()

emptyArray = ["", "", "西"]

// 插入元素, 则 emptyArray 的数组元素个数为 4 个, 之前的 0 为后移

emptyArray.insert("一路向西", at:0)

// 遍历数组中的元素

for 字符串 in emptyArray {

    print(字符串)

}

// 修改元素

emptyArray[1] = "三个女人"

for 字符串 in emptyArray {

    print(字符串)

}

// 区间运算符 

// a...b, 表示从a 到 b 且包含a 和 b

// a..<b 表示从a 到 b, 且包含a, 不包含 b

for 整数 in 1...10 {

    print(整数)

}

for 整数 in 5..<9 {

    print(整数)

}

// 替换并添加数组中的元素

emptyArray[2...3] = ["苍井空的故事", "苍老师的故事0", "苍老师的故事1", "苍老师的故事2"]

for 字符串 in emptyArray {

    print(字符串)

}

// 删除数组中的元素

emptyArray.removeLast()

for 字符串 in emptyArray {

    print(字符串)

}

 

let range = (0 ..< 1) // 移除 0

emptyArray.removeSubrange(range)

for 字符串 in emptyArray {

    print(字符串)

}

 

// 遍历数组中的下标, 和值

for (index, value) in emptyArray.enumerated() {

 print("index = \(index), value = \(value)")

    

}

 

print(emptyArray.count)

print(emptyArray.capacity) // 空间大小

 

// 字典

var emptyDict: Dictionary<Int, Int> = Dictionary()

var emptyDict2: [String : String] = Dictionary()

 

var studentDict = ["name" : "小明", "age" : 18, "gender" : ""] as [String : Any]

// 遍历字典中的所有key

for key in studentDict.keys {

    print(key)

}

// 遍历字典中的所有value

for value in studentDict.values {

    print(value)

}

// 遍历字典中的所有key ,value

for (key, value) in studentDict {

    print("key = \(key), value = \(value)")

}

// 删除字典中的数据

studentDict.removeValue(forKey: "age")

print(studentDict)

 

studentDict["gender"] = nil

print(studentDict)

// 插入值

studentDict["address"] = "你家里"

// 该方法, 如果字典中没有该key, 就增加一个键值对, 如果该key已存在, 就修改该key对象的value值

studentDict.updateValue(20, forKey: "age")

print(studentDict)

 

 

转载于:https://www.cnblogs.com/lurenq/p/7155437.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值