IT story

Swift에서 'get'과 'set'은 무엇입니까?

hot-time 2020. 9. 7. 21:25
반응형

Swift에서 'get'과 'set'은 무엇입니까?


저는 Swift를 배우고 The Swift Programming Language있으며 Apple에서 읽고 있으며 Objective C 배경이 없습니다 (PHP, JS 및 기타 만 있지만 Obj C는 없음).

24-25 페이지에 다음 코드가 표시됩니다.

//...Class definition stuff...

var perimeter: Double {
    get {
        return 3.0 * sideLength
    }
    set {
        sideLength = newValue / 3.0
    }
}

//...Class continues...

이 부분은 책에 명시되어 있지 않으며 그 내용을 알 수 없습니다.

누구든지 얻을 수 있고 설정 하는 것이 무엇인지 설명 할 수 있습니까 ?


실제로 코드 바로 앞에 설명되어 있습니다.

저장되는 단순 속성 외에도 속성에는 getter 및 setter가있을 수 있습니다.

class EquilateralTriangle: NamedShape {
    ...

다른 클래스가 해당 경계 변수를 얻으려고 할 때 다음을 수행합니다.

let someVar = myTriangle.perimeter

... 이것은 다음과 같습니다.

get{
    return 3.0 * self.sideLength
}

따라서 기본적으로 호출하는 컨트롤러가 다음을 수행 한 것과 같습니다.

let someVar = 3.0 * myTriangle.sideLength

다른 개체에서 변수 설정 하면 다음과 같습니다.

myTriangle.perimeter = 100

set{}블록 의 코드를 호출합니다 .

set {
    sideLength = newValue / 3.0
}

따라서 변수를 설정하는 클래스가 다음을 수행 한 것과 같습니다.

myTriangle.sideLength = 100/3.0

정말 편리 합니다. 항상 3으로 나누거나 곱하지 않고도 다른 코드에서 이것을 호출 할 수 있습니다. 왜냐하면 변수를 설정하기 직전과 변수를 얻기 직전에 이루어지기 때문입니다.

Swift에서 우리는 얻을 때 계산되고 설정 될 때 뭔가를 할 수있는 속성을 가질 수 있습니다. Objective-C에서도이 작업을 수행 할 수 있습니다.

// .h
@property (nonatomic) double perimeter;

//.m

- (double)perimeter
{
    return self.sideLength * 3.0;
}
- (void)setPerimeter:(double)perimeter
{
    self.perimeter = perimeter; // In Swift, this is done automatically.
    self.sideLength = perimeter / 3.0;
}

클래스 내에서 변수를 가져오고 설정하는 것은 내용을 검색 ( "가져 오기")하거나 변경 ( "설정")하는 것을 말합니다.

members클래스 의 변수 고려하십시오 family. 당연히이 변수는 정수가되어야합니다. 가족은 사람이 2 점으로 구성 될 수 없기 때문입니다.

So you would probably go ahead by defining the members variable like this:

class family {
   var members:Int
}

This, however, will give people using this class the possibility to set the number of family members to something like 0 or 1. And since there is no such thing as a family of 1 or 0, this is quite unfortunate.

This is where the getters and setters come in. This way you can decide for yourself how variables can be altered and what values they can receive, as well as deciding what content they return.

Returning to our family class, let's make sure nobody can set the members value to anything less than 2:

class family {
  var _members:Int = 2
  var members:Int {
   get {
     return _members
   }
   set (newVal) {
     if newVal >= 2 {
       _members = newVal
     } else {
       println('error: cannot have family with less than 2 members')
     }
   }
  }
}

Now we can access the members variable as before, by typing instanceOfFamily.members, and thanks to the setter function, we can also set it's value as before, by typing, for example: instanceOfFamily.members = 3. What has changed, however, is the fact that we cannot set this variable to anything smaller than 2 anymore.

Note the introduction of the _members variable, which is the actual variable to store the value that we set through the members setter function. The original members has now become a computed property, meaning that it only acts as an interface to deal with our actual variable.


A simple question should be followed by a short, simple and clear answer.

  • When we are getting a value of the property it fires its get{} part.

  • When we are setting a value to the property it fires its set{} part.

PS. When setting a value to the property, SWIFT automatically creates a constant named "newValue" = a value we are setting. After a constant "newValue" becomes accessible in the property's set{} part.

Example:

var A:Int = 0
var B:Int = 0

var C:Int {
get {return 1}
set {print("Recived new value", newValue, " and stored into 'B' ")
     B = newValue
     }
}

//When we are getting a value of C it fires get{} part of C property
A = C 
A            //Now A = 1

//When we are setting a value to C it fires set{} part of C property
C = 2
B            //Now B = 2

You should look at Computed Properties

In your code sample, perimeter is a property not backed up by a class variable, instead its value is computed using the get method and stored via the set method - usually referred to as getter and setter.

When you use that property like this:

var cp = myClass.perimeter

you are invoking the code contained in the get code block, and when you use it like this:

myClass.perimeter = 5.0

you are invoking the code contained in the set code block, where newValue is automatically filled with the value provided at the right of the assignment operator.

Computed properties can be readwrite if both a getter and a setter are specified, or readonly if the getter only is specified.

참고URL : https://stackoverflow.com/questions/24699327/what-are-get-and-set-in-swift

반응형