🖥️
iOS App with Pop
UIKit Swift 5
UIKit Swift 5
  • iOS App development
  • Swift
    • Variable & Constant
    • Number & String
    • Operator
    • Array, Dictionary & Tuple
    • Enum
    • Optional
    • Function
    • Class & Struct
    • Branching
    • Loops
    • Error handler
    • Protocol
    • Extension
  • Create New Project
  • Introduction to Xcode
  • Scene-Based Life-Cycle
  • UIViewController
  • Storyboard
  • First Run
  • Display todo list
  • Basic Auto Layout
  • MVC
  • Model
  • Binding TableView
  • Binding TableViewCell
  • TableViewDelegate
  • Add navigationBar with + button
  • Add new item page
  • TextField and Switch
  • Binding action
  • Add mock item to todo list
  • What is weak?
  • Finish add item
  • Delete todo item
  • Edit todo item
  • Custom new layout
  • Adding new delegate
  • Refactor
  • Pushing edit view
  • Large navigation
  • Drag item
  • Drop item (in app)
  • Save data
  • Where to go from here?
Powered by GitBook
On this page
  • Math Operators
  • Logical Operators
  • Range Operators
  1. Swift

Operator

Math Operators

Math operators ก็จะเหมือนในภาษาอื่น ๆ เช่น + - * / % เช่น

var x = 5
x = x + 1
x = 5 - x

+ เรายังสามารถใช้ concat ทั้ง String และ Array ได้ด้วย

let names = ["Pop"] + ["John"]

ในการหารเอาเศษเรามักจะใช้ % เช่น

let remainder = 17 % 5
// remainder = 2

แต่ใน swift เราสามารถเขียนให้อ่านเป็นประโยคได้แบบนี้

17.remainder(dividingBy: 5)

ในภาษาอื่น ๆ จะมี operator ++ เพื่อใช้ increment ค่าทีละ 1 เช่น

x = 0
x++    // Unary operator '++' cannot be applied

เนื่องจากถ้าใช้งานได้ มักจะทำให้เกิดความกำกวม เช่น x = x+++++x ทำให้ภาษา Swift ตัด operator นี้ทิ้งไป จึงทำให้เขียนได้แค่แบบนี้

x = x + 1
x += 1

Logical Operators

นอกจาก Operators ทางคณิตศาสตร์ Swift ก็ยังมี Operators ทางตรรกศาสตร์แบบภาษาอื่น ๆ เช่น

  • && แทน และ

  • || แทน หรือ

  • ! แทน นิเสธ

มี Operators ในการเปรียบเทียบ

  • == เปรียบเทียบค่าเท่ากัน

  • != เปรียบเทียบค่าไม่เท่ากัน

  • > เปรียบเทียบค่าซ้ายมากกว่า

  • >= เปรียบเทียบค่าซ้ายมากกว่าหรือเท่ากับ

  • < เปรียบเทียบค่าซ้ายน้อยกว่า

  • <= ในการ เปรียบเทียบค่าซ้ายน้อยกว่าหรือเท่ากับ

ในการเปรียบเทียบว่า เป็น object instance เดียวกันหรือไม่จะใช้ === หรือ !== เช่น

if obj1 === obj2 {
  // do something 
}

Range Operators

Swift ยังมี Range Operators ให้ใช้งานด้วย เช่น

  • Close range operator ... เช่น numbers range ตั้งแต่ 0 ถึง 5

    let numbers = 0...5
  • Half-open range operator ..< เช่น numbers range ตั้งแต่ 0 ถึง4

    let numbers = 0..<5
  • One-side range operator มักใช้ใน index ของ Array เช่น

    let a = [-1,-2,-3,0,1,2,3]
    let b = a[2...]      // b = [-3,0,1,2,3]
    let c = a[...2]      // c = [-1,-2,-3]
    let e = a[..<2]      // d = [-1,-2]
PreviousNumber & StringNextArray, Dictionary & Tuple

Last updated 2 years ago