IT박스

Swift References에서 _ 밑줄은 무엇입니까?

itboxs 2020. 6. 24. 07:50
반응형

Swift References에서 _ 밑줄은 무엇입니까?


Apple 문서의 참조 섹션에는 이런 종류의 인스턴스가 많이 있습니다.

func runAction(_action: SKAction!)

이것의 Objective-C '등가'는 다음과 같습니다.

- (void)runAction:(SKAction *)action

(Swift 참조에서) 밑줄 뒤에 공백이 있고 "동작"이 이탤릭체로 작성되는 것이 중요하다는 사실이 나에게 잘 맞습니다.

그러나 이것이 무엇을 전달하려고하는지 알 수 없습니다. 아마도 질문은 ... 참고 문헌에 사용 된 규칙에 대한 참조가 있습니까?

-아래 참조에서 밑줄 사용을 참조하는 페이지는 다음과 같습니다. https://developer.apple.com/documentation/spritekit/sknode#//apple_ref/occ/instm/SKNode/runAction

최신 정보

Swift 3에서는 함수 / 메소드 매개 변수 이름과 인수 레이블의 사용 및 이름 지정 방식이 일부 변경되었습니다. 이것은이 질문과 그 대답에 영향을 미칩니다. @Rickster는이 부분을 대부분 지우는 함수에서 _underscores에 대한 다른 질문에 대답하는 놀라운 일을합니다. 여기에 왜 신속하게 밑줄이 필요합니까?


두 대답 모두 정확했지만 조금 더 명확하게하고 싶습니다.

_메소드의 외부 매개 변수 이름 동작수정 하는 데 사용됩니다 .

에서 로컬 및 방법에 대한 외부 매개 변수 이름 문서의 섹션은 말한다 :

Swift는 기본적으로 메소드 의 첫 번째 매개 변수 이름에 로컬 매개 변수 이름을 제공하고 기본적으로 두 번째 이후의 매개 변수 이름을 로컬 및 외부 매개 변수 이름 으로 지정합니다.

반면 기본적으로 함수에는 외부 매개 변수 이름이 없습니다.

예를 들어,이 foo()메소드는 클래스에 정의되어 있습니다 Bar.

class Bar{
    func foo(s1: String, s2: String) -> String {
        return s1 + s2;
    }
}

당신이 전화하면 foo(), 같은 것 bar.foo("Hello", s2: "World")입니다.

그러나 , 당신은 사용하여이 동작을 무시할 수 있습니다 _앞에 s2가 선언 어디.

func foo(s1: String, _ s2: String) -> String{
    return s1 + s2;
}

그런 다음을 호출 하면 두 번째 매개 변수의 이름이없는 foo것처럼 간단하게 호출 될 수 있습니다 bar.foo("Hello", "World").

귀하의 경우로 돌아 가면 , 분명히 runActiontype과 관련되어 있기 때문에 방법 SKNode입니다. 따라서 _before 매개 변수를 action사용하면 runAction외부 이름없이 호출 할 수 있습니다 .

Swift 2.0 업데이트

함수 및 메소드는 이제 로컬 및 외부 인수 이름 선언 측면 에서 동일한 방식으로 작동 합니다 .

함수는 이제 기본적으로 2 번째 파라미터부터 외부 파라미터 이름을 사용하여 호출됩니다. 이 규칙은 순수한 Swift 코드에만 적용됩니다.

따라서 함수_ 앞에 함수 를 제공하면 호출자가 메서드에 대해 수행하는 것처럼 외부 매개 변수 이름을 지정할 필요가 없습니다 .


밑줄은 삭제 된 값을 나타내는 데 사용되는 일반 토큰입니다.

이 특정 경우, 함수가 runAction(argument)대신 함수가 호출됨을 의미합니다.runAction(action:argument)

다른 맥락에서 그것은 다음과 같은 다른 유사한 의미를 가지고 있습니다.

for _ in 0..<5 { ... }

즉, 블록을 5 회만 실행하고 블록 내의 인덱스는 신경 쓰지 않습니다.

이와 관련하여 :

let (result, _) = someFunctionThatReturnsATuple()

그것은 우리가 튜플의 두 번째 요소가 무엇인지 신경 쓰지 않고 첫 번째 요소 만 신경 쓰라는 것을 의미합니다.


매개 변수 선언 앞의 식별자는 외부 매개 변수 이름을 정의합니다 . 함수를 호출 할 때 호출자가 제공해야하는 이름입니다.

func someFunction(externalParameterName localParameterName: Int)

외부 이름을 직접 제공하지 않으면 Swift는 사용자가 정의한 기본 매개 변수에 대한 자동 외부 이름을 제공합니다. 외부 매개 변수 이름에 밑줄을 사용하면이 동작에서 제외됩니다.

_매개 변수를 정의 할 때 명시적인 외부 이름 대신 밑줄 ( ) 을 작성하여이 동작을 거부 할 수 있습니다 .

이 동작에 대한 자세한 내용은 여기 에서 기본값이있는 매개 변수의 외부 이름 섹션을 참조 하십시오 .


Swift 3부터 모든 인수 레이블이 기본적으로 필요합니다 .

IDE로 강제로 인수 레이블을 숨길 수 있습니다 _.

func foo(a: String) {
}

func foo2(_ a: String) {
}

전화 foo(a: "abc")foo2("abc")

참고 : 경우에만 사용할 수 a는 IS (외부) 인수 라벨(내부) 변수 명 을 동시에. 동등합니다- func foo(a a: String)을 (를) 수락하지 않습니다 _.

Apple에서 왜 사용하고 있습니까?

You can see Apple is using it across the API. Apple's libraries are still written in Objective-C (if not, they share the same function names anyway, which were designed for Objective-C syntax)

Functions like applicationWillResignActive(_ application: UIApplication) would have redundant parameter name application, since there is already the application in it's function name.

Your example

func runAction(_ action: SKAction!) would be called without it's _ mark like runAction(action:). The parameter name action would be redundant since there is already one in the function name. That's the purpose and why it's there.


I think this forces a convention in Swift that makes it read closer to objective-c, which matches cocoa conventions better. In objc you don't (externally) name your first parameter. Instead, by convention you usually include the external name in the latter part of the method name like this:

- (void)myFancyMethodWithFirstName:(NSString *)aFirstName lastName:(NSString *)aLastName;

[someInstance myFancyMethodWithFirstName:@"John" lastName:@"Doe"];

To make Swift api calls consistent with objc you will want to suppress the external parameter name of the first param.

func myFancyMethodWithFirstName(_ firstName:String, lastName:String);

someInstance.myFancyMethodWithFirstName("John", lastName:"Doe")

Actually, there is a difference between the real code used to define a method and the method declaration in Apple's docs. Let's take UIControl's - addTarget:action:forControlEvents: method for example, the real code is: enter image description here

But in docs, it appear like this (notice _ before target): enter image description here

In real code, _ is used to make the second or subsequent parameter's external name not appear when a method is called, while in docs, _ before a parameter's local name indicates that when you call a method or a function, you should not provide an external name.

There's no external name when a function is called by default unless you provide your own or add # before (without whitespace) a parameter's local name, for example, this is how we use dispatch_after: enter image description here

And in docs, it appear like this (notice three _): enter image description here

The convention of function's declaration is just the same as I have described for method.


Just more visually.

enter image description here

As you can see the _ just make omit a local parameter name or not.

참고URL : https://stackoverflow.com/questions/24437388/whats-the-underscore-representative-of-in-swift-references

반응형