Swift学习:10.运算符

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

1.基本运算符

1)一元运算符

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

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

  • 问题?答案1:答案2

2.重载运算符

@H_404_136@Struct Sword{

@H_404_136@ var length: Float

@H_404_136@ var weight:Float

@H_404_136@ var name :String

@H_404_136@}

@H_404_136@//重载运算符“+”

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

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

@H_404_136@ weight : left.weight + right.weight,

@H_404_136@ name: “Big Sword”)

@H_404_136@}

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

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

@H_404_136@ return Sword(length: -sword.length,

@H_404_136@ weight: - sword.weight,

@H_404_136@ name: “Small Sword”)

@H_404_136@}

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

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

@H_404_136@ var oldSword = Sword

@H_404_136@ sword.length += 1.0

@H_404_136@ sword.weight += 1.0

@H_404_136@ return oldSword

@H_404_136@}

3.自定义运算符

@H_404_136@infix operator +-* {associativity left precedence 140}

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

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

@H_404_136@ weight:left.weight + right.weight,

@H_404_136@ name:left.name + right.name)

@H_404_136@}

@H_404_136@第一段: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

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

猜你在找的Swift相关文章