Swift 3 – Structs !
Classes and structures are general-purpose, flexible constructs that become the building blocks of your program’s code. You define properties and methods to add functionality to your classes and structures by using exactly the same syntax as for constants, variables, and functions.
we define it with the struct followed by a name of the struct then open braces then close braces.
Inside the braces is where your properties go. Properties are like attributes of the struct.
struct User {
var username: String
var email: String
var name: String
}
Structs are complex data types, meaning that they are made up of multiple values. You then create an instance of the struct and fill in its values, then you can pass it around as a single value in your code.
import UIKit
// Method-1
struct studentMarks {
var mark1 = 100
var mark2 = 200
var mark3 = 300
}
// Method-2
struct MarksStruct
{
var mark: Int
init(mark: Int) {
self.mark = mark
}
}
class ViewController: UIViewController
{
override func viewDidLoad() {
super.viewDidLoad()
// Method-1
let marks = studentMarks()
print("Mark1 is \(marks.mark1)")
print("Mark2 is \(marks.mark2)")
print("Mark3 is \(marks.mark3)")
// Method-2
var aStruct = MarksStruct(mark: 98)
var bStruct = aStruct // aStruct and bStruct are two structs with the same value!
bStruct.mark = 97
print(aStruct.mark)
print(bStruct.mark)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Discover more from CODE t!ps
Subscribe to get the latest posts sent to your email.