programing

Swift 클래스의 정적 vs 클래스 함수/변수?

sourcejob 2023. 5. 14. 10:35
반응형

Swift 클래스의 정적 vs 클래스 함수/변수?

Swift 1.2에서 컴파일되는 코드는 다음과 같습니다.

class myClass {
    static func myMethod1() {
    }
    class func myMethod2() {
    }
    static var myVar1 = ""
}

func doSomething() {
    myClass.myMethod1()
    myClass.myMethod2()
    myClass.myVar1 = "abc"
}

정적 함수와 클래스 함수의 차이점은 무엇입니까?어떤 것을 언제 사용해야 합니까?

다른 변수를 정의하려는 경우class var myVar2 = ""다음과 같이 표시됩니다.

클래스에서 아직 클래스 저장 속성이 지원되지 않습니다. 'static'을 의미합니까?

이 기능이 지원되는 경우 정적 변수와 클래스 변수(즉, 둘 다 클래스에 정의된 경우)의 차이점은 무엇입니까?어떤 것을 언제 사용해야 합니까?

(Xcode 6.3)

static그리고.class둘 다 메서드를 클래스의 인스턴스가 아닌 클래스와 연결합니다.차이점은 하위 클래스가 다음을 재정의할 수 있다는 것입니다.class메서드; 메서드를 재정의할 수 없습니다.static방법들.

class 속성은 동일한 방식으로 작동합니다(하위 클래스는 속성을 재정의할 수 있음).

운동장에서 미파디의 답변과 댓글을 시도해봤습니다.그리고 그것을 공유하려고 생각했습니다.여기 있어요.저는 미파디의 답변이 받아들여진 것으로 표시되어야 한다고 생각합니다.

class A{
    class func classFunction(){
    }
    static func staticFunction(){
    }
    class func classFunctionToBeMakeFinalInImmediateSubclass(){
    }
}

class B: A {
    override class func classFunction(){
        
    }
    
    //Compile Error. Class method overrides a 'final' class method
    override static func staticFunction(){
        
    }
    
    //Let's avoid the function called 'classFunctionToBeMakeFinalInImmediateSubclass' being overriden by subclasses
    
    /* First way of doing it
    override static func classFunctionToBeMakeFinalInImmediateSubclass(){
    }
    */
    
    // Second way of doing the same
    override final class func classFunctionToBeMakeFinalInImmediateSubclass(){
    }
    
    //To use static or final class is choice of style.
    //As mipadi suggests I would use. static at super class. and final class to cut off further overrides by a subclass
}

class C: B{
    //Compile Error. Class method overrides a 'final' class method
    override static func classFunctionToBeMakeFinalInImmediateSubclass(){
        
    }
}

OOP와 관련하여 답은 너무 간단합니다.

하위 클래스는 클래스 메서드를 재정의할 수 있지만 정적 메서드는 재정의할 수 없습니다.

게시물 외에도 클래스 변수를 선언하려는 경우(사용자가 한 것처럼)class var myVar2 = ""), 다음과 같이 수행해야 합니다.

class var myVar2: String {
    return "whatever you want"
}

Swift 4에서의 테스트는 시뮬레이터의 성능 차이를 보여줍니다.저는 "class func"로 수업을 만들고 "static func"로 structure를 만들어서 테스트를 진행했습니다.

정적 함수:

  • 컴파일러 최적화 없이 20%빨라짐
  • 최적화 -스캐너 -스캐너 -최적화를 사용할 경우 38% 더 빨라집니다.

그러나 iOS 10.3에서 아이폰 7에서 동일한 코드를 실행하는 것은 정확히 동일한 성능을 보여줍니다.

당신이 스스로를 테스트하고 싶다면 https://github.com/protyagov/StructVsClassPerformance 의 Xcode 9를 위한 Swift 4의 샘플 프로젝트입니다. https://github.com/protyagov/StructVsClassPerformance

저는 제 프로젝트 중 하나에서도 이런 혼란을 겪었고, 이 게시물이 매우 도움이 된다는 것을 알게 되었습니다.제 놀이터에서도 똑같이 해봤는데요, 여기 요약이 있습니다.이것이 저장된 속성과 유형의 기능을 가진 누군가에게 도움이 되기를 바랍니다.static,final,class학급 대표 등을 무시함.

class Simple {

    init() {print("init method called in base")}

    class func one() {print("class - one()")}

    class func two() {print("class - two()")}

    static func staticOne() {print("staticOne()")}

    static func staticTwo() {print("staticTwo()")}

    final func yesFinal() {print("yesFinal()")}

    static var myStaticVar = "static var in base"

    //Class stored properties not yet supported in classes; did you mean 'static'?
    class var myClassVar1 = "class var1"

    //This works fine
    class var myClassVar: String {
       return "class var in base"
    }
}

class SubSimple: Simple {
    //Successful override
    override class func one() {
        print("subClass - one()")
    }
    //Successful override
    override class func two () {
        print("subClass - two()")
    }

    //Error: Class method overrides a 'final' class method
    override static func staticOne() {

    }

    //error: Instance method overrides a 'final' instance method
    override final func yesFinal() {

    }

    //Works fine
    override class var myClassVar: String {
        return "class var in subclass"
    }
}

다음은 테스트 샘플입니다.

print(Simple.one())
print(Simple.two())
print(Simple.staticOne())
print(Simple.staticTwo())
print(Simple.yesFinal(Simple()))
print(SubSimple.one())
print(Simple.myStaticVar)
print(Simple.myClassVar)
print(SubSimple.myClassVar)

//Output
class - one()
class - two()
staticOne()
staticTwo()
init method called in base
(Function)
subClass - one()
static var in base
class var in base
class var in subclass

빠른 클래스 대 정적

[참조 vs 값 유형]

class내부에서 사용됨Reference Type(클래스, 함수):

  • 계산된 속성
  • 방법
  • 하위 클래스에서 재정의할 수 있습니다.

static내에서사됨용 안에서 됩니다.Reference Typefunction) 및 (lass, function) 및Value Type enum, 숫, 열, 튜):

  • 계산된 속성 및 저장된 속성
  • 방법
  • 하위 클래스에서 변경할 수 없습니다.
protocol MyProtocol {
//    class var protocolClassVariable : Int { get }//ERROR: Class properties are only allowed within classes
    static var protocolStaticVariable : Int { get }
    
//    class func protocolClassFunc()//ERROR: Class methods are only allowed within classes
    static func protocolStaticFunc()
}

struct ValueTypeStruct: MyProtocol {
    //MyProtocol implementation begin
    static var protocolStaticVariable: Int = 1
    
    static func protocolStaticFunc() {
        
    }
    //MyProtocol implementation end
    
//    class var classVariable = "classVariable"//ERROR: Class properties are only allowed within classes
    static var staticVariable = "staticVariable"

//    class func classFunc() {} //ERROR: Class methods are only allowed within classes
    static func staticFunc() {}
}

class ReferenceTypeClass: MyProtocol {
    //MyProtocol implementation begin
    static var protocolStaticVariable: Int = 2
    
    static func protocolStaticFunc() {
        
    }
    //MyProtocol implementation end
    
    var variable = "variable"

//    class var classStoredPropertyVariable = "classVariable"//ERROR: Class stored properties not supported in classes

    class var classComputedPropertyVariable: Int {
        get {
            return 1
        }
    }

    static var staticStoredPropertyVariable = "staticVariable"

    static var staticComputedPropertyVariable: Int {
        get {
            return 1
        }
    }

    class func classFunc() {}
    static func staticFunc() {}
}

final class FinalSubReferenceTypeClass: ReferenceTypeClass {
    override class var classComputedPropertyVariable: Int {
        get {
            return 2
        }
    }
    override class func classFunc() {}
}

//class SubFinalSubReferenceTypeClass: FinalSubReferenceTypeClass {}// ERROR: Inheritance from a final class

점이 더 있어요: 다점하더있습다니나이른▁there다있니.class계산된 유형의 유형 속성만 정의하는 데 사용할 수 있습니다.저장된 유형 속성이 필요한 경우static대신.

static 키워드를 사용하여 유형 특성을 정의합니다.클래스 유형에 대한 계산된 유형 속성의 경우 class 키워드를 대신 사용하여 하위 클래스가 수퍼 클래스의 구현을 재정의하도록 허용할 수 있습니다.

https://docs.swift.org/swift-book/LanguageGuide/Properties.html

위의 답변에 정적 메서드가 정적 디스패치라는 것은 정적 메서드를 재정의할 수 없기 때문에 컴파일러가 런타임에 실행될 메서드를 알고 있다는 것을 의미하며, 클래스 메서드는 동적 디스패치이며 하위 클래스는 이러한 메서드를 재정의할 수 있습니다.

언급URL : https://stackoverflow.com/questions/29636633/static-vs-class-functions-variables-in-swift-classes

반응형