Created
October 27, 2021 23:57
-
-
Save phptuts/2b88ea75143ff1900b423201e2f18306 to your computer and use it in GitHub Desktop.
Swift Structs Demo
This file contains hidden or 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
import UIKit | |
struct User { | |
var email: String | |
var username: String | |
} | |
// Structs come with a prebuilt init function | |
var user = User(email: "[email protected]", username: "green") | |
// Structs copy data on write here is an example | |
var tom = User(email: "r", username: "s") | |
var jill = tom | |
jill.email = "blue" | |
print("Jill's Email: \(jill.email)") | |
print("Tom's Email: \(tom.email)") | |
// Structs can use private and public member variables but you must provide the init constructor | |
struct Person { | |
public var name: String | |
private var age: Int | |
public init(_ name: String) { | |
self.age = 0 | |
self.name = name | |
} | |
public mutating func addYear() -> Person { | |
self.age += 1 | |
return self | |
} | |
public func getYear() -> Int { | |
return self.age | |
} | |
private func sayHi() -> String { | |
return "Hi, my name \(self.name) and I am \(self.getYear()) old" | |
} | |
public func sayHello() { | |
print(self.sayHi()) | |
} | |
} | |
var james = Person("James") | |
print("HELLO") | |
james.addYear() | |
james.sayHello() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment