The operator for Swift notes

  • 2020-05-10 22:59:42
  • OfStack

Null value merge operator and interval operator

Today's focus is on the basic operators in Swift. Record 1.

Nil Coalescing Operator

a & # 63; The & # 63; b the & # 63; The & # 63; This is the null value merge operator, which determines a. If it is not nil, unpack it; otherwise, it returns b.


var a: String? = "a"
var b: String? = "b"
var c = a ?? b   // "a"
a = nil
c = a ?? b     // "b"
b = nil
c = a ?? b ?? "c"  // "c"

There are two requirements when using it:

a must be optional
b must correspond to a type 1
In other words, a 1 must have the possibility to be a spare tire, and b 1 must have the qualification to be a spare tire.

This is a shorthand for the 3-byte operator:


a != nil ? a! : b or a == nil ? b : a!

You can also do this with a custom operator:


infix operator ||| {}

func |||<T> (left: T?, right: T) -> T {
  if let l = left { 
    return l 
  }
  return right
}

var a:String?
var b = "b"
var c = a ||| b

C# also has an ? The & # 63; If you are interested, you can learn 1.

Range Operator

Interval operators are divided into closed intervals (...) And left closed right open interval (.. < ) two, the former is to calculate the head to calculate the tail, the latter is to calculate the head not to calculate the tail.

Can be applied in switch:


switch aNumber
{
case 0...5:
  println("This number is between 0 and 5")
case 6...10:
  println("This number is between 6 and 10")
default:
  println("This number is not between 0 and 10")
}

The interval operator actually returns an Range < T > Object, which is a collection of consecutive uncorrelated sequence indexes.

Before the words left closed right open is.. , which is the exact opposite of Ruby...

But some people just want to use... , so you can write one by yourself like this:


infix operator .. { associativity none precedence 135}

func .. (lhs: Int, rhs: Int) -> Range<Int> {
  return lhs..<rhs
}

for i in 0..10 {
  println("index \(i)")
}

You can also use generate() to traverse:


var range = 1...4
var generator = range.generate()  // {startIndex 1, endIndex 5}
generator.next() // 1
generator.next() // 2
generator.next() // 3
generator.next() // 4
generator.next() // nil

.generate () returns 1 RangeGenerator < T > Can be used to traverse Range < T > The value.

There used to be a (5... 1).by(-1), but it doesn't seem to work now.

The interval operator returns one ClosedInterval or HalfOpenInterval, as long as the type is Comparable. So we can also put String into... In the water.

For example, cat's Swifter Tips has a chapter code as follows, which outputs the lowercase letters in the string through String's ClosedInterval:


let test = "Hello"
let interval = "a"..."z"

for c in test {
  if interval.contains(String(c)) {
    println("\(c)")
  }
}

SubString

It is convenient to get SubString by dot and dot:


2.1.3 :001 > a="abc"
 => "abc"
2.1.3 :002 > a[0]
 => "a"
2.1.3 :003 > a[0..1]
 => "ab"

And ClosedInterval in Swift doesn't have subscript. But what are we going to do with the [1...3] method?
Write extension, just add subscript, and the subscript type is Range < Int > Ok:


extension String {
  subscript (r: Range<Int>) -> String {
    get {
      let startIndex = advance(self.startIndex, r.startIndex)
      let endIndex = advance(startIndex, r.endIndex - r.startIndex)

      return self[Range(start: startIndex, end: endIndex)]
    }
  }
}

var s = "Hello, playground"

println(s[0...5]) // ==> "Hello,"
println(s[0..<5]) // ==> "Hello"

If you want to search for the target string and then intercept substring, you can do this:


let name = "Joris Kluivers"

let start = name.startIndex
let end = find(name, " ")

if (end != nil) {
  let firstName = name[start..<end!]
} else {
  // no space found
}

That's all for this article, I hope you enjoy it.


Related articles: