Swift 4 - Basic You Must Know to Learn Swift
If you a beginner in programming language swift or you’ve ever tried to learn Swift, but you don't know where to start
let’s start with the lessons :
1. Variable
let = Constant -> you cannot change value data
var = Dynamic -> you can change value data
example:
let dataConstan: String = "Hello" // example let
data.text = dataConstan
Print(data) // result is -> Hello
var dataDynamic: String = "Hello" // example var
dataDynamic = "Hi"
Print(dataDynamic) // result is -> Hi
2. Data Type
berikut ini kita akan membahas tipe data yang digunakan pada pemmograman swift.
Int = 1, 2, 3, 10, dst // data yang bersifat angka
String = “ Hello ” // data yang bersifat huruf di awali dengan tanda kutip dua (“ ”) dan di akhiri dengan data yang sama.
Float = 2.3456, 3.478, 0.2 // adalah tipe data yang menggunakan angka desimal 32- bit
Double = 2.3456, 3.478, 0.2 // adalah tipe data yang menggunakan angka desimal 64 - bit, tipe data ini lebih sering digunakan.
Bool = True, false // tipe data Boolean yang mana data yang bisa digunakan hanya dua tipe saja antara True atau False
Character = “C”, “D”, “A” // tipe data dari single - string karakter
3. If a statement
Here is an example of flow from If Statement
Image: Flow Chart If Statement 1.0
If statement -> For example if the statement can see the code below. which in this example uses the true condition, meaning that if it is correct, it will print "Hi If".
if condition == true {
print ("Hi if")
}
If else Statement -> Same as the condition if above, it will use another condition or we call it "If not" as in Picture: Flow Diagram If Statement 1.0.
if condition == true {
print ("Hi if")
} other {
print ("Hi others")
}
4. Switch Statements
On swift using Switch Statements is an alternative to If Statements. In its simplest form, Statements switches compare values to one or more values of the same type.
value switch {
case value 1:
response value 1
case value 2:
response value 1
default:
return default
}
5. Loops
Looping or looping is a method of finding data other than the if else statement. The following are some types of loops, namely for - in, and while loop.
for-in loop -> This type of loop is most commonly used which is to search for data such as Array, a range of numbers, character on strings, and Collection Items.
Example on Array data:
let names = ["Budi", "nisa", "Brian"]
for name in names {
print ("Hello, \ (name)!")
}
6. Function
This function is used with the key "func" in programming swift, used to classify the code which will be called on the main body or we usually call viewDidLoad (), viewDidAppear (), and the like body play.
import UIKit
ExampleVC class: UIViewController {
override func viewDidLoad () {
super.viewDidLoad ()
example () // how to call func
}
func example () {
print ("Example")
}
}
7. Class
Classes are an important part of building or creating an application using the Swift programming language, this class uses almost the same as a struct, the difference is that the class has several types that can affect changes in the status class. For the initial writing, the class name must use uppercase letters, like the others that also use uppercase letters at the beginning of the word: protocol, class, struct, extension.
Example class without class type:
class Example {
var name: String?
var dateBorn: Int?
}
Example class uses type class:
class Example: UIViewController {
override func viewDidLoad () {
super.viewDidLoad ()
}
}
Classes have many types such as UIViewController, UITableViewCell, UICollectionViewCell and many more depending on function or need. to create a class like an example above which starts with the "{" (parenthesis) or called Brackets and ends with the "}" close, so the variable, func, enum, viewDidLoad, and other data types are in the sign.
8. Struct
For structs itself is a mini version of the class, which is used to make it easier to create variables, and also save coding, can be used again in other classes, when calling certain classes. Here's a sample class.
An example if struct has its own separate file "ExampleStruct.swift":
ExampleStruct {struct
var name: String
var age: Int
}
Then it can be called in a class like the following:
class Example: UIViewController {
override func viewDidLoad () {
super.viewDidLoad ()
let data Example = ExampleStruct (name: "Me", age: 20)
print ("Name: \ (data example.name)")
print ("Age: \ (data example.age)")
}
}
Result/results on Debug Area:
My name
Age: 20
9. Initializers
It is the process of preparing init from a class, struct or enum to be used, init and setting or initializing it as needed before new instances are ready to be used.
Here is an example of init which is inside the struct.
ExampleStruct struct
{
var id: String
var value: String
var category: String
click var: String
init (dict: [String: Any])
{
self.id = dict ["id"] as! String
self.value = dict ["value"] as! String
self.category = dict ["category"] as! String
self.click = dict ["click"] as! String
}
}
10. Optional "?" & Unwrapping "!"
Which optional uses the sign "? "Often used in data and value types, to call properties. Conditions for using Optional "? "If the data received has the possibility of Nile / Null, or the data received is unknown. As for the sign "! "Is for the data received there must be or to force the data to exist.
Examples of variables:
var keyword: String? // Optional
var keyword: String! // Unrapping
If you find an error when running Run app "Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value" one of the possibilities is like the following example
print (data.item!)
Then get the error as above, then the solution that can be used is to use Optional "?? ", The following is the solution code.
print (data.item ?? "") // String
print (data.item ?? 0) // Int
Explanation: if the data received is there (data.item -> sample contents are data string "Existing") then the data will be displayed if the result is not optional ("") empty string.
11. Array
Array is a data that is often used, where this array stores many elements in it or a collection of data can be one data type or more different data types. For creators in square brackets "[]" separated by a comma "," as the following example:
// Array type Int
let numbers = [1, 3, 5, 7, 9]
// String type array
var words = ["Boat", "fruit", "Car", "Bike"]
// Empty Arrays are often used for data input processes.
emptyString var: [String] = []
Examples in Full Program:
import UIKit
class ExampleViewController: UIViewController {
@IBOutlet weak var textField1: UITextField!
@IBOutlet weak var tableView: UITableView!
var dataArray: [String] = []
override func viewDidLoad () {
print (dataArray)
}
@IBAction func bAddAction (_ sender: UIButton) {
self.dataArray.append (textField1.text!)
print (dataArray)
}
}
12. Dictionary
This dictionary is a collection of elements that are paired together in an array, using a key (key) such as a string and int, which string as key and int as the value or contents of the data.
The following example is how to check API / database data using an integer key type
var responseMessages = [200: "OK", 403: "Access forbidden", 404: "File not found", 500: "Internal server error"]
print (responseMessages)
Example type of empty dictionary
empty var var: [String: String] = [:]
emptyDict var: [String: Int] = [:]
emptyDict var: [Int: String] = [:]
empty var var: [String: Double] = [:]
etc.
Examples in Full Program:
import UIKit
class ExampleViewController: UIViewController {
var exampleNumbers: [String: Int] = ["one": 4, "two": 2, "three": 6]
override func viewDidLoad () {
super.viewDidLoad ()
print ("Example Dictionary: \ (exampleNumbers.description)")
}
}
Reference:
https://docs.swift.org/swift-book/
https://developer.apple.com/documentation/swift
No comments: