You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesi贸n a prueba de IA

Antes: $249

Currency
$209
Suscr铆bete

Termina en:

2 D铆as
9 Hrs
58 Min
54 Seg

Clases y herencia

17/25
Resources

How to define a class in Swift?

The Swift language offers unique features for object-oriented programming. One of the fundamental elements is the definition of classes, which is distinguished by a specific structure. Let's create a Student class in Swift and examine its key differences with a struct.

import Foundation public class Student { var name: String let age: Int var email: String var subjects: [Subject] var scores: [Double] public init(name: String, age: Int, email: String, subjects: [Subject], scores: [Double]) { self.name = name self.age = age self.email = email self.subjects = subjects self.scores = scores } public func studentDescription() -> String { // Implementation of the student description return "" } }

What makes classes in Swift special?

Classes in Swift are essential because of their ability to support inheritance, which means that one class can inherit properties and methods from another. This allows for hierarchical structure and code reuse. For example, an AdvancedStudent class can inherit from Student:

public class AdvancedStudent: Student { var extraPoints: Double public init(name: String, age: Int, email: String, subjects: [Subject], scores: [Double], extraPoints: Double) { self.extraPoints = extraPoints super.init(name: name, age: age, email: email, subjects: subjects, scores: scores) } override public func studentDescription() -> String { // Specialized implementation of AdvancedStudent return "AdvancedStudent" } }

How to initialize a class instance in Swift?

Creating instances of a class in Swift is straightforward. Here we show how to initialize a Student and an AdvancedStudent, using their unique properties and methods to generate custom descriptions.

let student1 = Student(name: "Thiago", age: 18, email: "[email protected]", subjects: [mathSubject], scores: [70]) let student2 = AdvancedStudent(name: "Maria", age: 19, email: "[email protected]", subjects: [mathSubject], scores: [80], extraPoints: 10) print(student1.studentDescription()) print(student2.studentDescription())

Why use classes instead of structs?

The crucial difference between class and struct in Swift lies in the inheritance capability of classes. In object-oriented programming, this is essential for extending the behavior of classes and reusing code efficiently. While classes allow you to create complex, custom hierarchies, structs are more efficient for data structures that do not need to inherit properties or methods.

Practical example of using advanced classes

Classes allow you to implement custom behaviors, which is essential for cases such as advanced learners with additional features. Let's imagine that we want to add an extra grading system for completed assignments, something that is possible thanks to inheritance and override in Swift.

override public func studentDescription() -> String { var description = super.studentDescription() description += " - ExtraPoints: \(extraPoints)" return description }

This use of inheritance and override in Swift allows us to generate complex systems in an understandable and efficient way.

Let's move on!

Learning Swift and object-oriented programming opens up a world of possibilities for creating powerful and efficient applications. Practice defining more classes and experimenting with inheritance in your own projects.

Contributions 2

Questions 0

Sort by:

Want to see more contributions, questions and answers from the community?

```js public func studentDescription() -> String{ var description = """ ------------------- STUDENT: ------------------- #Name: \(name) #Age: \(age) #Email: \(email) #Actual Subjects: """ for (subject,score) in zip(subjects,scores) { description += """ \(subject.subjectDescription()) Score: \(score) """ } description += "\n-------------------" return description } ```
Yo lo hice con un map que me de devolviera el string que ya ejecuta el struct de Subject, con un formateo para separar cada uno, pero como el map devuelve un array de strings, le agregu茅 al final una funci贸n de "joined" con el separador de salto de l铆nea "\n", para que ahora si fuera un string multil铆nea de todas las materias, al final solo puse esta variable en el formateo del return final. ```js public func studentDescription() -> String { let subjectDescriptions: String = subjects.map { subject in """ # \(subject.subjectDescription()) +++++++++++++++++++++++++++++++++ """ }.joined(separator: "\n") return """ ****************** Student descrition ****************** # Name: \(name) # Age: \(age) # E-mail: \(email) # Subjects: \(subjectsDescriptions) # Grades? \(grades) """ } ```