SeaWarrior404
SeaWarrior404

Reputation: 4167

What is the meaning of "public init() { } " in Swift 3?

I'm fairly new to Swift and I've been trying to learn how to implement a stack in Swift 3. In some of the reference code I found online for implementing the stack structure, I came across public init() {}. What does it mean?

    public struct Stack<T> {
    private var elements = [T]()

    public init() {}

    public mutating func push(element: T) {
        self.elements.append(element)
    }

    public mutating func pop() -> T? {
        return self.elements.popLast()
    }

    public mutating func peek() -> T? {
        return self.elements.last
    }

    public func isEmpty() -> Bool {
        return self.elements.isEmpty
    }

    public func count() -> Int {
        return self.elements.count
    }
}

Upvotes: 1

Views: 4928

Answers (5)

Sergey
Sergey

Reputation: 1617

From documentation:

Open access and public access enable entities to be used within any source file from their defining module, and also in a source file from another module that imports the defining module. You typically use open or public access when specifying the public interface to a framework. The difference between open and public access is described below.

This mean you can use this constructor within any source file.

Upvotes: 0

Ishika
Ishika

Reputation: 2205

When you mark public, the thing gets available outside of the framework in which your code has been implemented whereas init() {} is a swift initializer that is responsible for ensuring the object is fully initialized. Basically initializers are called to create a new instance of a particular type. In its simplest form, an initializer is like an instance method with no parameters.

init() {
    // perform some initialization here
}

Upvotes: 11

ios
ios

Reputation: 31

your answer with comment:

public class SomePublicClass {                  // explicitly public class
        public var somePublicProperty = 0            // explicitly public class member
        var someInternalProperty = 0                 // implicitly internal class member
        fileprivate func someFilePrivateMethod() {}  // explicitly file-private class member
        private func somePrivateMethod() {}          // explicitly private class member
    }

Upvotes: 1

Sneha
Sneha

Reputation: 2216

Initializers are called to create a new instance of a particular type. In its simplest form, an initializer is like an instance method with no parameters, written using the init keyword. Public access is typically used when specifying the public interface to a framework.

For more details, refer https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Initialization.html

Upvotes: 0

va05
va05

Reputation: 325

The main purpose is to initialize the object , its a constructor. For further details check this out

Upvotes: 0

Related Questions