Structures
There is a way to create new types in Swift using structures.
// This is how you declare a new struct
struct Song {
let title: String
let artist: String
let duration: Int
var rating: Int //This property can be changed **notice the var declaration all the others are constants let
}
// And this is how a type strct is created
let song = Song(title: "No, no, no", artist: "Fizz", duration: 150, rating: 4)
//This is how each property is called
song.rating // this will return 4
song.rating = 5 // this will change the 4 for a 5 Int
Calculated Properties
struct Song {
let title: String
let artist: String
let duration: Int
var formattedDuration: String {
let minutes = duration / 60
// The modulus (%) operator gives the remainder
let seconds = duration % 60
return "\(minutes)m \(seconds)s"
}
var formattedTitle: String {
return "\(title) by \(artist)"
}
}
let song = Song(title: "No, no, no", artist: "Fizz", duration: 150)
song.formattedDuration // "2m 30s"
song.formattedTitle // "No, no, no by Fizz"
Functions
struct Rectangle {
let width: Int
let height: Int
}
// If you wanted to find out if one rectangle is larger than another, you could define a function like this:
func isRectangle(_ rectangle: Rectangle, biggerThan rectangle2: Rectangle) -> Bool {
let areaOne = rectangle.height * rectangle.width
let areaTwo = rectangle2.height * rectangle2.width
return areaOne > areaTwo
}
// Then you could use the function to compare two rectangles:
let rectangle = Rectangle(width: 10, height: 10)
let anotherRectangle = Rectangle(width: 10, height: 30)
print(rectangle)
isRectangle(rectangle, biggerThan: anotherRectangle)
Instance Methods
struct Rectangle {
let width: Int
let height: Int
func isBiggerThan(_ rectangle: Rectangle) -> Bool {
let areaOne = width * height
let areaTwo = rectangle.width * rectangle.height
return areaOne > areaTwo
}
}
// Notice that within the body of the method definition, you can access the values of `height` and `width` of the struct without using a dot. The instance method is written as part of the struct definition, and so it can directly access the properties within the instance.
// Just like the methods on built-in types, the methods you define are called using the instance name, then a dot, then the name and arguments of the method:
let rectangle = Rectangle(width: 10, height: 10)
let otherRectangle = Rectangle(width: 10, height: 20)
rectangle.isBiggerThan(otherRectangle) //returns false
otherRectangle.isBiggerThan(rectangle) //returns true