create a class in swift

To create a class in Swift, you first need to declare it using the class keyword followed by the class name. After that, you can define properties and methods inside the class.

main.swift
class MyClass {
   // define properties and methods here
}
59 chars
4 lines

Here's an example for creating a class Person with two properties name and age:

main.swift
class Person {
   var name: String
   var age: Int
   
   init(name: String, age: Int) {
      self.name = name
      self.age = age
   }
   
   func sayHello() {
      print("Hello, my name is \(name) and I am \(age) years old.")
   }
}
238 chars
14 lines

In the above example, we have created a class Person with two properties name and age, and a method sayHello that prints a greeting message. The init method is the initializer for the class that takes in two parameters name and age.

gistlibby LogSnag