Swift学习:10.运算符

前端之家收集整理的这篇文章主要介绍了Swift学习:10.运算符前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

1.基本运算符

1)一元运算符

  • 自增自减运算符:++ --
  • 正号负号运算符:+ -
  • 逻辑非运算符:!
2)二元运算符

  • 赋值运算符:a = b
  • 算数运算符:+ = * /
  • 求余运算符:%
  • 符合赋值运算符: += -= *= /=
  • 比较运算符: == != > < >= <=
  • 空合运算符:?? a ?? b 相当于 a != nil ? a! : b
  • 区间运算符:a...b a..<b
  • 逻辑与或运算符:&& ||
3)三木运算符

  • 问题?答案1:答案2

2.重载运算符

Struct Sword{

var length: Float

var weight:Float

var name :String

}

//重载运算符“+”

func +(left: Sword,right:Sword)->Sword{

return Sword(length : left.length + right.length,

weight : left.weight + right.weight,

name: “Big Sword”)

}

//重载前置运算符“-”

prefix func-(sword:Sword)->Sword{

return Sword(length: -sword.length,

weight: - sword.weight,

name: “Small Sword”)

}

//重载后置运算符“++”

postfix func++(inout Sword)->Sword{

var oldSword = Sword

sword.length += 1.0

sword.weight += 1.0

return oldSword

}

3.自定义运算符

infix operator +-* {associativity left precedence 140}

func +-*(left: Sword,right:Sword)->{

return Sword(length:left.length + right.length,

weight:left.weight + right.weight,

name:left.name + right.name)

}

第一段:operator infix/prefix/postfix自定义运算符{}
第二段:infix/prefix/postfix func (参数表) ->返回类型{}

4.示例代码

println("Hello,World!")


let name = "sn"


let dog:Character = "a"

let cow:Character = "b"

//let dogCow = dog + cow


let contentHeight = 40

let hasHead = true

let roheight = contentHeight + (hasHead ? 50 : 20)


for index in 1...5

{

println(index)

}

let names = ["a","b","c","d"]

let countNumber = names.count

for index in 0..<countNumber

{

println(names[index])

}

for name in names

{

if name.hasPrefix("c"){

println("1")

}

}


for character in "asfedee"

{

println(character)

}


let heart = "\u{2665}"

println(heart)

let unusualMenagerie = "Koala

版权声明:本文为博主原创文章,未经博主允许不得转载。

原文链接:https://www.f2er.com/swift/327163.html

猜你在找的Swift相关文章