美文网首页
swift 4数据类型

swift 4数据类型

作者: 艺术农 | 来源:发表于2018-05-30 09:43 被阅读17次
  • 如何定义一个指定类型的数据
let wantADouble = 3 //let wantADouble: Int = 3
let actuallyDouble = Double(3)
let actuallyDouble: Double = 3
let actuallyDouble = 3 as Double
  • 字符和字符串定义
//定义字符类型需要显示指定其类型
let characterA: Character = "a"
let characterDog: Character = "🐶"
let stringDog: String = "Dog"
let stringDog = "Dog" // Inferred to be of type String
  • 字符串拼接
var message = "Hello" + " my name is "
let name = "Matt"
message += name // "Hello my name is Matt”

//非字符串类型拼接需要强制类型转换
let exclamationMark: Character = "!"
message += String(exclamationMark) // "Hello my name is Matt!”

let zhang = "zhang"
let number = 3
var zhangsan = zhang + String(number)
  • 字符串插入
message = "hello my name is \(name)" // "Hello my name is Matt!"
let oneThird = 1.0 / 3.0
let oneThirdLongString = "One third is \(oneThird) as a decimal."

“One third is 0.3333333333333333 as a decimal.”

以这种方式插入double类型的缺点是无法控制输出长度

  • 多行字符串
    swift通过三个双引号来定义多行字符串,需要注意的是开头和结尾的双引号不属于字符串的内容需要单独为一行。此外,多行字符串格式是以结尾的三个双引号为参考对齐,注意书写格式。
let bigStr = """
    you can have a string
  that contains multiple
    lines
  by doing
  this.
  """
print(bigStr)
  • 元组(Tuples)
    swift提供了更简单的办法来处理诸如:二维坐标,3D坐标这种数据的方法。
  1. 不带变量名元组的定义与访问
let coordinate3D = (1, 2.1, 3)
print(coordinate3D.0, coordinate3D.1, coordinate3D.2)//通过索引来访问
  1. 带变量名元组的定义与访问
let coordinate3D = (x: 1, y : 2.1, z : 3)
print(coordinate3D.x, coordinate3D.y, coordinate3D.z)
let (x3, y3 ,z3) = coordinate3D
print(x3, y3, z3)
  1. 下划线
    如果你想忽略元组某个部分,可以用下划线来替代这个位置。
let (x4, y4, _) = coordinates3D

相关文章

网友评论

      本文标题:swift 4数据类型

      本文链接:https://www.haomeiwen.com/subject/hhftsftx.html