Some of the access control settings in Swift language are detailed _swift

Source: Internet
Author: User
Tags constant switch case

Restricting access to code blocks, modules, and abstractions are accomplished through access control. Classes, structs, and enumerations can be accessed through the access control mechanism based on their own properties, methods, initialization functions, and subscripts. The Protocol restrictions for constants, variables, and functions, and allow access control to access global and local variables. The access control applied to attributes, types, and functions can be called "entities."

The access control model is based on modules and source files.

The module definition assigns a separate unit to the code and can be imported using the Import keyword. The source file is defined as a single source code file, and the module has access to multiple types and functions.

Three different levels of access are provided by the Swift language. They are public, Internal, and Private access respectively.

Grammar

Copy Code code as follows:

public class Somepublicclass {}
Internal class Someinternalclass {}
Private class Someprivateclass {}

public var somepublicvariable = 0
Internal Let Someinternalconstant = 0
Private Func Someprivatefunction () {}




access control for function types
Some functions may have parameters in the function declaration but do not have any return values. The following program declares that A and B are passed as arguments to the sum () function. The intrinsic function itself is the value of parameters A and B by calling the function sum (), whose value is printed so that the value is not returned. To make the return type of a function private, the declaration function uses private to decorate the overall access level.


Copy Code code as follows:

Private func sum (A:int, b:int) {
Let A = a + b
Let B = A-b
println (A, B)
}

SUM (20, 10)
SUM (40,10)
SUM (24,6)




When we use playground to run the above program, we get the following results

(a)
(m)
(30, 24)

Access control for enumerated types

Copy Code code as follows:

public enum student{
Case Name (String)
Case Mark (Int,int,int)
}
var studdetails = student.name ("Swift")
var studmarks = Student.mark (98,97,95)
Switch Studmarks {
Case. Name (Let Studname):
println ("Student name is: \ (studname).")
Case. Mark (Let-Mark1, let-Mark2, let Mark3):
println ("Student Marks are: \ (MARK1), \ (MARK2), \ (MARK3).")
Default
println ("Nothing")
}



When we use playground to run the above program, we get the following results

Student Marks are:98,97,95

Enumerations automatically receive enumerated individuals in the swift language and have the same access level. For example, consider access fixed to three account enumeration names, students whose names and tags are declared as student and those that exist in the enumeration class are string data type names, tokens are represented as MARK1, MARK2 and MARK3 data types are integers. To access either the student name or Mark score. Now, if the Switch case block is executed, the student name will be printed, otherwise it will print a fixed mark by the student. If both of these conditions fail, the default block is executed.

Child class access control
Swift allows a user subclass of any class that can be accessed in the current access context. Subclasses cannot have a higher level of access than their superclass classes. User restricts the writing of a common subclass to an internal superclass.

Copy Code code as follows:

public class Cricket {
Private func print () {
println ("Welcome to Swift Super Class")
}
}

Internal class Tennis:cricket {
Override internal Func print () {
println ("Welcome to Swift Sub Class")
}
}

Let cricinstance = Cricket ()
Cricinstance.print ()

Let tennisinstance = Tennis ()
Tennisinstance.print ()




When we use playground to run the above program, we get the following results

Welcome to Swift Super class
Welcome to Swift Sub class

constants, variables, attributes, and subscript access control
Swift constant, a variable or property cannot be defined more openly than its type. This is invalid a public attribute and a private type. Similarly, the subscript cannot be more open than its index or return type.

When a constant, variable, attribute, or subscript uses a private type, constants, variables, attributes, or subscripts, must also be marked as private:

Copy Code code as follows:
private var privateinstance = Someprivateclass ()

Getters and Setters
getter and setter constants, variables, attributes, and labels automatically receive constants, variables, attributes, or subscripts that belong to the same access level.
Copy Code code as follows:

Class SAMPLEPGM {
private var counter:int = 0{
Willset (newtotal) {
println ("Total Counter are: \ (newtotal)")
}
didset{
If counter > OldValue {
println ("newly Added Counter \ (counter-oldvalue)")
}
}
}
}

Let Newcounter = SAMPLEPGM ()
Newcounter.counter = 100
Newcounter.counter = 800




When we use playground to run the above program, we get the following results

Total Counter is:100
newly Added Counter total
Counter is:800 newly Added Counter
700

Initialization of access control and default initializer
Custom initialization functions can be allocated an access level less than or equal to the type they initialize. A required initialization must have the same access level because they are the same as the class. The type of an initialization parameter cannot be more intimate (or higher) than initializing its own access level.

Declare each and every subclass, and the "required" keyword needs to be defined before the Init () function.

Copy Code code as follows:

Class ClassA {
Required Init () {
var a = 10
println (a)
}
}

Class Classb:classa {
Required Init () {
var B = 30
println (b)
}
}

Let res = ClassA ()
Let print = CLASSB ()




When we use playground to run the above program, we get the following results

Ten
10

The default initialization has the same access level because it is initialized unless the type is defined as a public type. When the default initialization is defined as public it is considered internal. When the user needs a common type to initialize in a parameterless initialization in another module, explicitly provides a common parameterless initialization as part of the type definition.

Access control for a protocol
when we define a new protocol, inherited functionality from existing protocols, both declare the same access level to inherit attributes from each other. Swift access control allows the user to define the "public" protocol, which inherits from the "internal" protocol.

Copy Code code as follows:



Public protocol Tcpprotocol {


Init (No1:int)


}

public class MainClass {
var no1:int//Local Storage
Init (no1:int) {
Self.no1 = no1//initialization
}
}

Class Subclass:mainclass, Tcpprotocol {
var no2:int
Init (No1:int, No2:int) {
Self.no2 = NO2
Super.init (NO1:NO1)
}

Requires only one parameter for convenient
Required Override convenience init (No1:int) {
Self.init (No1:no1, no2:0)
}
}

Let res = MainClass (no1:20)
Let print = Subclass (no1:30, no2:50)

println ("res is: \ (res.no1)")
println ("res is: \ (print.no1)")
println ("res is: \ (PRINT.NO2)")




When we use playground to run the above program, we get the following results

Res is:20
Res is:30
Res is:50

Extended access Control
when users use extensions to add consistency to the protocol, Swift does not allow users to provide an explicit access level modifier for the extension. For an extension of each protocol, the default access level required for implementation sets its own protocol access level.

For generic access control
generics allow the user to specify a minimum access level to access the type constraint for the type parameter.

Copy Code code as follows:

public struct Tos<t> {
var items = [T] ()
Private mutating func push (item:t) {
Items.append (item)
}

Mutating func pop ()-> T {
Return Items.removelast ()
}
}

var tos = tos<string> ()
Tos.push ("Swift")
println (Tos.items)

Tos.push ("generics")
println (Tos.items)

Tos.push ("Type Parameters")
println (Tos.items)

Tos.push ("Naming Type Parameters")
println (Tos.items)
Let Deletetos = Tos.pop ()




When we use playground to run the above program, we get the following results

[Swift]
[Swift, generics]
[Swift, generics, Type Parameters]
[Swift, generics, type Parameters, naming type Parameters]

For type alias access control
A user can define a type alias to treat different access control types. The same access level or different access level can be defined by the user. When the type alias is "private" and its associated member can be declared "private, internal public type." When the type alias is a public member and cannot be a name that is alias "internal" or "private"

Defines that any type alias is considered to be used for different types of access control purposes. A type alias can have an access level of a type that is less than or equal to one of its access level aliases. For example, a private type alias can be aliased to private, internal, or public, whereas a public type alias cannot be aliased to a internal or private type.

Copy Code code as follows:



Public protocol Container {


Typealias ItemType


Mutating func append (item:itemtype)


var count:int {Get}


Subscript (i:int)-&gt; ItemType {get}


}

struct Stack<t>: Container {
Original stack<t> Implementation
var items = [T] ()
mutating func push (item:t) {
Items.append (item)
}

Mutating func pop ()-> T {
Return Items.removelast ()
}

Conformance to the Container protocol
Mutating func Append (item:t) {
Self.push (item)
}

var Count:int {
Return Items.Count
}

Subscript (i:int)-> T {
return Items[i]
}
}

Func allitemsmatch<
C1:container, C2:container
where C1. ItemType = = C2. ItemType, C1. Itemtype:equatable>
(SOMECONTAINER:C1, ANOTHERCONTAINER:C2)-> Bool {
Check that both containers contain the same number of items
If Somecontainer.count!= anothercontainer.count {
return False
}

Check each pair of the items to if they are equivalent
For I in 0..<somecontainer.count {
If Somecontainer[i]!= Anothercontainer[i] {
return False
}
}

All items match, so return true
return True
}

var tos = stack<string> ()
Tos.push ("Swift")
println (Tos.items)

Tos.push ("generics")
println (Tos.items)

Tos.push ("Where Clause")
println (Tos.items)

var eos = ["Swift", "Generics", "Where Clause"]
println (EOS)




When we use playground to run the above program, we get the following results

[Swift]
[Swift, generics]
[Swift, generics, where Clause]
[Swift, generics, where Clause]

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.