Trong bài viết trước chúng ta đã tìm hiểu được Tại sao nên học Swift ?. Bây giờ chúng ta sẽ bắt đâu tìm hiểu về các dữ liệu và biến trong Swift. Cũng tương tự như các ngôn ngữ lập trình khác, ngôn ngữ Swift cũng bao gồm nhiều kiểu dữ liệu khác nhau để giúp chúng ta tạo nên các dữ liệu để xử lý trong ứng dụng và dùng các kiểu dữ liệu chúng ta sẽ tạo nên các biến.
Ngoài các dữ liệu cơ bản mà ngôn ngữ nào cũng có thì Swift còn hỗ trợ thêm các kiểu dữ liệu riêng mà chúng ta sẽ tìm hiểu qua bài hướng dẫn này.
Để bắt đầu cho bài hướng dẫn này, các bạn nên sử dụng Xcode Playground để thực hành code theo các ví dụ trong bài, nó giúp bạn sẽ dễ hiểu và nhớ lâu hơn.Chạy Xcode 8, tạo mới một Playground và tiến hành hoc.
1. Biến (Variables)
- var là cú pháp để khai báo một biến giá trị(trị của biến đó có thể thay đổi),
- let là cú pháp để khai báo một biến hằng(giá trị của biến đó sẽ không được thay đổi trong quá trình sử dụng) .
Có 2 cách khai bào, một là khai báo không tường mình:
Ví dụ:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var street = “101, Phan Chu Trinh, Tam Ky, Quang Nam” | |
let number = 10 |
Khai kháo một biến tường minh:
Ví dụ:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var street: String = “101, Phan Chu Trinh, Tam Ky, Quang Nam” | |
let number: Int = 10 |
Tóm lại, chúng ta cần xác định mục đích của biến cần tạo, về sau nó có thay đổi giá trị hay không mà từ đó sử dụng từ khóa tương ứng var hoạc let.
2. Các kiểu dự liệu trong Swift.
Như các bạn đã biết hầu như mọi ngôn ngữ lập trình điều có kiểu dữ liệu và Swift cũng không ngoại lệ. Trong bài này chúng ta sẽ tìm hiểu những kiến thức cơ bản và tổng quát về các kiểu dữ liệu trong Swift,
Trong Swift đều có tất cả các kiểu dữ liệu cơ bản trong C và Objective-C bao gồm:
- Int (Int32, Int64)
Ví dụ:
let meaningOfLife = 42
- Float
Ví dụ:
let pi: Float = 3.14159
- Double
Ví dụ:
let abc =103.14159
- Character
Ví dụ:
let key: Character = “8”
- String
Ví dụ:
let value= “12434 Vinh 123”
Lưu ý: Khi tạo một biết thập phân thì trình biên dịch sẽ tự ưu tiên và hiểu biến đó là kiểu Double, nếu muốn khai báo kiểu Float thì chúng ta phải khai báo biến một cách tường mình.
Ví dụ:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let total = 10.5 // Biến total kiểu Double | |
let range: Float = 10.5 // Biến range kiểu Float |
Các kiểu dữ liệu tập hợp (Collection types):
Aray
- Tập hợp các trị cùng dữ liệu và được sắp xếp có thứ tự.
Ví dụ:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var someInts = [Int]() | |
print(“someInts is of type [Int] with \(someInts.count) items.”)// In ra console “someInts is of type [Int] with 0 items.” | |
var threeDoubles = Array(repeating: 0.0, count: 3)// threeDoubles có kiểu dữ liệu là [Double], và có trị là [0.0, 0.0, 0.0] | |
var shoppingList: [String] = [“Eggs”, “Milk”,”Flour”] | |
// shoppingList được khởi tạo với 3 phần tử | |
for item in shoppingList { | |
print(item) | |
} | |
// Six eggs | |
// Milk | |
// Flour | |
for (index, value) in shoppingList.enumerated() { | |
print(“Item \(index + 1): \(value)“) | |
} | |
// Item 1: Six eggs | |
// Item 2: Milk | |
// Item 3: Flour |
Set
- Tập hơp các trị khác kiểu dữ liệu và không có thứ tự
Ví dụ:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var letters = Set<Character>()print(“letters is of type Set with \(letters.count) items.”) | |
// In ra console “letters is of type Set with 0 items.” | |
var favoriteGenres: Set<String> = [“Rock”, “Classical”, “Hip hop”] | |
// favoriteGenres Khởi tạo giá trị với 3 phần tử | |
var favoriteGenres: Set = [“Rock”, “Classical”, “Hip hop”] | |
for genre in favoriteGenres { | |
print(“\(genre)”) | |
} | |
// Jazz | |
// Hip hop// Classical | |
for genre in favoriteGenres.sorted() { | |
print(“\(genre)“) | |
} | |
// Classical | |
// Hip hop | |
// Jazz |
Lưu ý:
- Để in giá trị ra màn hình console chúng ta dùng từ khóa print(…).
- Giá trị trong Set phải được thực thi protocol Hashable , Tại sao lại thực thi protocol Hashable? Vì trong Hashable lại thực thi protocol Equatable và trong Equatable có toán tử == , toán tử này cần thiết trong quá trình so sánh và truy xuất tới các phần tử trong Set.
- Mặc định các kiểu dữ liệu cơ bản trong Swift đều thực thi protocol Hashable (String, Int, Double, Bool)
Dictionary
- Tập hợp các giá trị khác nhau, không có thứ tự, được truy xuất giá trị theo key nên key phải duy nhất.
Ví dụ:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var namesOfIntegers = [Int: String]() | |
// namesOfIntegers là một Dictionary rỗng kiểu [Int: String] | |
var airports: [String: String] = [“YYZ”: “Toronto Pearson”, “DUB”: “Dublin”] | |
hoặc | |
var airports = [“YYZ”: “Toronto Pearson”, “DUB”: “Dublin”] | |
airports[“LHR”] = “London” | |
// Bây giờ thì biến airports dictionary chứa 3 phần tử. | |
if let oldValue = airports.updateValue(“Dublin Airport”, forKey: “DUB”) { | |
print(“The old value for DUB was \(oldValue).”) | |
} | |
for (airportCode, airportName) in airports { | |
print(“\(airportCode): \(airportName)”) | |
} | |
// DUB: Dublin Airport | |
// YYZ: Toronto Pearson | |
// LHR: London Heathrow | |
for airportCode in airports.keys { | |
print(“Airport code: \(airportCode)”) | |
} | |
// Dublin Airport: DUB | |
// Airport code: YYZ | |
// Airport code: LHR | |
for airportName in airports.values { | |
print(“Airport name: \(airportName)”) | |
} | |
// Airport name: Dublin Airport | |
// Airport name: Toronto Pearson | |
// Airport name: London Heathrow |
Lưu ý: Kiểu dữ liệu của key trong Dictionary cũng phải được thực thi protocol Hashable tương tự như kiểu dữ liệu Set.
Ngoài dữ liệu quen thuộc, Swift còn cung cấp một số dữ liệu nâng cao không có trong Objective-C như:
- Tuples:
- Là một nhóm các dữ liệu được gôm lại trong cặp dấu ().
- Một Tuples có thể chứa nhiều kiểu dữ liệu khác nhau.
Ví dụ:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let http404Error = (404, “Not Found”)// http404Error is of type (Int, String), and equals (404, “Not Found”) |
Cách để truy cập biến Tuples:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let (statusCode, statusMessage) = http404Errorprint(“The status code is \(statusCode)“)// Prints “The status code is 404” | |
print(“The status message is \(statusMessage)“)// In ra console “The status message is Not Found” | |
print(“The status code is \(http404Error.0)“)// In ra console “The status code is 404” | |
print(“The status message is \(http404Error.1)“)// In ra console “The status message is Not Found” | |
let http200Status = (statusCode: 200, description: “OK”) | |
print(“The status code is \(http200Status.statusCode)“)// In ra console “The status code is 200” | |
print(“The status message is \(http200Status.description)“)// In ra console “The status message is OK” |
Lưu ý: Nên dùng Tuples cho một nhóm các giá trị có mối liên quan tới nhau và chứa các trị cụ thể nào đó. Bạn có thể thấy như ví dụ ở trên.
Bạn có thể tham khảo bài sau để hiểu hơn về Array,Set,Dictionary,Tuples.
Bạn có thể tham khảo bài sau để hiểu hơn về Array,Set,Dictionary,Tuples.
Qua bài này các bạn sẽ biết được các kiểu dữ liệu trong Swift cũng như cách tạo ra một biến hoặc hằng. Hiểu được cách dùng để áp dụng nó vào trong các trường hợp cụ thể trong quá trình code để tăng hiểu xuất cho code và tránh lỗi xảy ra.
Hy vọng các bạn thích và học được nhiều kiến thức từ bài viết này. Mong các bạn chia sẽ nó để mọi người cùng học và cùng trao đổi. Mọi thắc mắc hay trao đổi về bài viết, các bạn có thể để lại bình luận bên dưới mình sẽ hỗ trợ sớm nhất.
Chân thành cảm ơn các bạn đã theo dõi.
Chân thành cảm ơn các bạn đã theo dõi.
VHX.
Bài viết liên quan:
1 Comments
Bài viết rất hay và bổ ích, cám ơn bạn rất nhiều.
ReplyDelete