Main.swift//Swift calculation Properties////Created by Goddog on 15/7/20. COPYRIGHT©2015 year Goddog.
All rights reserved.
Import Foundation print ("Swift's computed properties are similar to Java setter and Getter methods, enumerations, structs, classes can all define computed properties, all have set and get methods Oh")/** modifier var computed property name: property type
{get {//get method execution body, the method must have a return value} set () {//set method execution body, must not have a return value}} where modifiers, set can be omitted */ Enumeration defines a computed property enum Season {case Spring, Summer, Fall, Winter var info:string {//define Get method G et{print ("Get Method") switch (self) {case. Spring:return "Spring" Default:return "No"}}//define Set Method Set (NewValue) {print ("Set method") print ("Incoming parameter: \ (NewValue)")}}} var a = Seas On. Spring print (A.info)//is actually called getter method a.info = "Autumn"//actually called Setter method//The above example is simply assigned, and there is no real assignment class User {var first:string = "" var last:string = ""//define calculated properties
var fullname:string {//define the first, last two properties of the computed property determines get{return, "-" + Last }//define the set method of the computed property, change first, last two storage property set (NewValue) {var names = newvalue.componentsseparated Bystring ("-") Self.first = names[0] Self.last = names[1]}} init (First:stri Ng, last:string) {Self.first = First self.last = last}} let S = User (first: "Cao", Last: "F") p
Rint (S.fullname)//Call get method S.fullname = "Liu-ready" print ("FirstName: \ (S.first), LastName: \ (s.last)")//mark:-Setter Method Simplification /** the setter method of the computed property provides an implicit formal parameter name, newvalue above can be set{var names = newvalue.componentsseparatedbystring ("-") Self.first = n Ames[0] Self.last = names[1]} *///mark:-read-only computed properties//Only get parts, no calculated property of set part is called read-only computed property, and read-only computed attribute definition section can even omit get keyword and braces cla
SS Cat {var first:string = "" var last:string = ""//define read only computed attribute, only get part (omitted) var fullname:string { Return first + "-' + Last} ' init (first:string, last:string) {Self.first = First self.last = last}} let
Name = User (First: "Sun", Last: "Right") print (Name.fullname)//read-only computed property cannot be assigned, the program can only get the value of a read-only computed property