🖥️
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
  1. Swift

Variable & Constant

มาประกาศตัวแปรกันเถอะ

PreviousSwiftNextNumber & String

Last updated 2 years ago

การประกาศตัวแปรใน Swift จะมีหน้าตาการประกาศประมาณนี้

let <variable name>: <Type> = <Value>
var <variable name>: <Type> = <Value>

เช่น

let name: String = "pop"
var number: Int = 5

โดยที่ let จะใช้กับการประกาศตัวแปรที่เป็น constant นั่นคือจะไม่มีการเปลี่ยนแปลงค่า จนหมด scope ของตัวแปรนั้น

ส่วน var คือตัวแปรที่จะมีการเปลี่ยนแปลงค่าในภายหลัง

โดยปกติ Swift จะสามารถ infer type ของตัวแปรได้ทำให้เราสามารถละ Type ของตัวแปรได้ แต่ในบางครั้งเพื่อป้องกันความกำกวมเราก็จำเป็นต้องระบุลงไปด้วย

let implicitDouble = 70.0
let explicitDouble: Double = 70

ในบรรทัดที่ 2 ถ้าไม่กำหนด Type เป็น Double จะทำให้ infer type เป็น Int

ในระหว่างที่เราเขียนโค้ดอยู่นั้น ถ้าเราอยากรู้ Type ของตัวแปร ให้เรากด option + คลิ๊ก ที่ตัวแปรนั้น

โดยที่ชนิดตัวแปรที่สามารถใช้ได้ มีเยอะมาก โดยที่เราใช้หลัก ๆ จะมี String Int Double Float Bool Character Optional

นอกจากนี้เรายังสามารถ custom type ของเราได้ด้วย Enum, Struct และ Class

กด option + คลิ๊ก ที่ชื่อตัวแปรเพื่อดู Type ของตัวแปรนั้น