본문 바로가기

iOS

[iOS] Swift Attributes를 배워보자

docs.swift.org/swift-book/ReferenceManual/Attributes.html

Attributes — The Swift Programming Language (Swift 5.3)

Attributes There are two kinds of attributes in Swift—those that apply to declarations and those that apply to types. An attribute provides additional information about the declaration or type. For example, the discardableResult attribute on a function d

docs.swift.org

 

자바를 하신분들은 어노테이션에 익숙하지만, 저는 자알못이거든요..!

오늘은 코딩을 하다보면 남의 코드에서 볼 수 있는, 

Attributes를 배워보려고 합니다! 종류가 정말 많아요.

 

[사진 1]

 

함수 위에 @를 시작으로 하는 것들을 많이 보셨을텐데요! 특히 @objc @IBAction @IBOutlet ~

오늘은 이런 친구들을 다뤄볼겁니다. 아직 한 함수에 한 애트리뷰트만 적용할 수 있는데, (swift 5.3)

곧 여러 애트리뷰트가 동시에 적용되도록 바뀔 예정이라고 합니다.

 

 한번에 다루다 보니 자세하게는 못 다루겠지만, 이런 일을 하는군! 정도로 알아주세요~!

 

Declaration Attributes

선언형식에만 사용할 수 있습니다. 

 

1. discardableResult

 

이름으로 유추해보기 : 결과를 버릴수 있는 놈인가..?

도큐먼트 정의 :

Apply this attribute to a function or method declaration to suppress the compiler warning when the function or method that returns a value is called without using its result.

 

> 리턴형식이 있는 함수나 클로저, 메소드를 사용했을때 리턴값을 사용하지 않는 경우 발생하는 컴파일러 경고를 무시합니다 (suppress)

[그림 1]에서는 Completable 형식의 리턴값을 사용해도 되고, 사용하지 않아도 되겠죠?

 

2. available

 

이름으로 유추해보기 : 가능한 놈인가...?

도큐먼트 정의 :

Apply this attribute to indicate a declaration’s life cycle relative to certain Swift language versions or certain platforms and operating system versions.

The available attribute always appears with a list of two or more comma-separated attribute arguments. These arguments begin with one of the following platform or language names:

 

>  선언한 메소드나 속성의 생명주기에 관한 것인데, Swift 버전이나, OS 버전에 관련이 있도록 나타내는 것입니다.

 

[사진 2]

 

statusBar의 색상을 바꾸는 코드를 만들었는데요, `statusBarManager` 속성은 iOS 13에서 등장한 속성입니다.

따라서 iOS 13 이하의 버전에서는 red가 뜨도록 만들었는데, 결과는 잘 작동합니다

 

3. dynamicCallable

 

이름으로 유추해보기 : 동적으로 부를 수 있는 놈인가..?

도큐먼트 정의 :

Apply this attribute to a class, structure, enumeration, or protocol to treat instances of the type as callable functions.

The type must implement either a dynamicallyCall(withArguments:) method,  dynamicallyCall(withKeywordArguments:) method, or both.

 

> 클래스, 구조체, 열거형이나 프로토콜에에 이 형식을 적용해서 호출 가능한 함수처럼 다룰 수 있음!

> dynamicallyCall(withArguments:)  메소드나 dynamicallyCall(withKeywordArguments:) 둘 중 아무거나 혹은 둘다 구현해라!

 

아래의 예제 : Repeater Struct를 함수 인스턴스처럼 사용한 예제

 

[사진 3]  dynamicCallable

 

 

4. dynamicMemberLookup

 

이름으로 추론 : 동적인 멤버를 찾는다...?

도큐먼트 정의 :

Apply this attribute to a class, structure, enumeration, or protocol to enable members to be looked up by name at runtime. The type must implement a subscript(dynamicMemberLookup:) subscript.

 

> Class, Structure, Enum이나 프로토콜에 적용해서 런타임에 이름으로 멤버를 찾도록 하겠다

> subscript(dynamicMemberLookup:)를 구현해야만 한다 서브스크립트를 구현하세요

> 3번이랑 4번은 조금 신기함다

 

Dictionary의 Key를 String으로 받아서, 멤버가 있으면 Value를 리턴해주는 subscript 작성을 해 줍니다

 

[사진 4]

 

5. frozen. 프레임워크 관련 내용인것 같아서 생략. (실습도 없음)

6. GKInspectable SpriteKit 관련한 내용이여서 생략. (나중에 게임 만들면 해볼게요..)

 

7. inlinable

 

이름으로 추론 : Inline 함수들을 말하는 것일까..?

도큐먼트 정의 :

Apply this attribute to a function, method, computed property, subscript, convenience initializer, or deinitializer declaration to expose that declaration’s implementation as part of the module’s public interface. The compiler is allowed to replace calls to an inlinable symbol with a copy of the symbol’s implementation at the call site.

 

> 함수, 메소드, Computed Property, 이니셜라이저등에 적용하여 모듈의 공개적인 인터페이스의 일부로 외부에 노출시킨당

그런데 모듈얘기가 나온거니까...얘도 프레임워크 이야기 아닐까 하고 찾아봤더니

 

frozen, inlinable은 swift 4.2에 발표된 효율적인 프레임워크 구성 편에 있다... 그러니까 이런애가 있겠구나라고만 생각하고

나중에 사용할 때 다시 찾아보겠습니다!

 

8. main

 

이름으로 추론 : main함수가 들어가는 지점을 알려주는 앤가

도큐먼트 정의 :

Apply this attribute to a structure, class, or enumeration declaration to indicate that it contains the top-level entry point for program flow. The type must provide a main type function that doesn’t take any arguments and returns Void. For example:

 

> Structure, class, Enum에게 프로그램 플로우에서 가장 높은 레벨의 진입지점임을 가리키는 어노테이션

> 얘는 어느 매개변수도 가지지않고, Void를 리턴할것임을 무조건적으로 보장해야 한다

 

 

[사진 5]

 

 

9. nonObjc, objc

 

이름으로 추론 : objective-C의 잔해물이겠구나

도큐먼트 정의 : 

nonObjc

Apply this attribute to a method, property, subscript, or initializer declaration to suppress an implicit objc attribute. The nonobjc attribute tells the compiler to make the declaration unavailable in Objective-C code, even though it’s possible to represent it in Objective-C.

 

> 메소드, 프로퍼티나 Subscript, 이니셜라이저 등에 적용하는데, Objc 애트리뷰트를 강제로 무시함 (suppress)

> Objective-C 코드를 선언하지 못하도록 강제함

 

objc:

제일 많이 본 친구중 하나

Apply this attribute to any declaration that can be represented in Objective-C—for example, nonnested classes, protocols, nongeneric enumerations (constrained to integer raw-value types), properties and methods (including getters and setters) of classes, protocols and optional members of a protocol, initializers, and subscripts. The objc attribute tells the compiler that a declaration is available to use in Objective-C code.

 

> 말이 너무 어렵던데요

> 맨 밑에 줄 : The objc attribute tells the compiler that a declaration is available to use in Objective-C code.

> 컴파일러에게 Objective-C 코드에서도 선언이 유효함을 나타냄

> 대강 Objective-C 함수라고 알면 안 될까..

 

아직도 엄청 많습니다..그런데 여기서 중요하게 생각하고 많이 사용할것 같은건.....

1, 2번, 그리고 지금 할 10번.......

 

10. propertyWrapper

Swift Version 5.1에서 새로 나온 애트리뷰트

사아실 이 밑에도 위에서 한만큼 더 있는데...나중에...나중에... 다루겠습니다.

 

이름으로 추론 : 프로퍼티를 래핑해주는 놈이니..?

도큐먼트 정의 :

Apply this attribute to a class, structure, or enumeration declaration to use that type as a property wrapper. When you apply this attribute to a type, you create a custom attribute with the same name as the type. Apply that new attribute to a property of a class, structure, or enumeration to wrap access to the property through an instance of the wrapper type. Local and global variables can’t use property wrappers.

 

> class, structure, enum형에 선언해서, Property Wrapper처럼 사용하세요. 속성을 래핑하는 툴 처럼 사용하라는 건지? 

> 프로퍼티래퍼 속성을 적용하는 경우, 동일한 이름을 가진 애트리뷰트를 생성해야 합니다.

무슨 말인지 잘 모르겠어서, 구글링을 했습니다!

 

wlaxhrl.tistory.com/90

Property Wrapper

Swift 5.1 에서 추가된 Property Wrapper의 Apple Docs 번역글입니다. 제 블로그에서 Swift 번역글이 스테디하게 인기가 좋길래 새로운 피처가 추가된 기념으로 한번 해보았습니다 :) 제 번역 포스트는 원문

wlaxhrl.tistory.com

잘 설명이 되어있는 찜토끼님의 링크를 남깁니다.

 

 

'iOS' 카테고리의 다른 글

[iOS] Bundle과 Package에 대해서  (0) 2020.09.18
[iOS] Moya에 대해서 공부해보아요  (0) 2020.09.08
[iOS] Dependency Injection, (IoC, DI, DIP)  (0) 2020.08.21
[iOS] 객체지향과 SOLID 원칙 - Swift  (0) 2020.08.14
[iOS] throttle, debounce  (0) 2020.07.31