samsung-ga / woody-iOS-tip

🐶 iOS에 대한 소소한 팁들과 개발하다 마주친 버그 해결기, 그리고 오늘 배운 것들을 모아둔 레포
19 stars 0 forks source link

코드 스타일 컨벤션 정리 #11

Open samsung-ga opened 2 years ago

samsung-ga commented 2 years ago

본 컨벤션은 StyleShare의 swift-style-guide에서 가져왔습니다. 프로젝트에 들어가기 전, 다시 한번 숙지하기 위하여 작성해보았습니다. 이 외에도, 매 프로젝트에 들어가기 전에 정하면 좋을 것 같은 컨벤션들은 아래 몇가지가 더 있습니다.

목차

코드 레이아웃

들여쓰기 및 띄워쓰기

줄바꿈

func animationController( forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController ) -> UIViewControllerAnimatedTransitioning? { // doSomething() }


- 함수를 호출하는 코드가 최대 길이를 초과하는 경우에는 파라미터 이름을 기준으로 줄바꿈한다.

```swift
let actionSheet = UIActionSheet(
  title: "정말 계정을 삭제하실 건가요?",
  delegate: self,
  cancelButtonTitle: "취소",
  destructiveButtonTitle: "삭제해주세요"
)
UIView.animate(
  withDuration: 0.25,
  animations: {
    // doSomething()
  },
  completion: { finished in
    // doSomething()
  }
)
if let user = self.veryLongFunctionNameWhichReturnsOptionalUser(),
  let name = user.veryLongFunctionNameWhichReturnsOptionalName(),
  user.gender == .female {
  // ...
}
guard let user = self.veryLongFunctionNameWhichReturnsOptionalUser(),
  let name = user.veryLongFunctionNameWhichReturnsOptionalName(),
  user.gender == .female
else {
  return
}

최대 줄 길이

빈 줄

// MARK: Layout

override func layoutSubviews() {
  // doSomething()
}

// MARK: Actions

override func menuButtonDidTap() {
  // doSomething()
}

임포트

import UIKit

import SwiftyColor
import SwiftyImage
import Then
import URLNavigator

네이밍

클래스

함수

// ✅
func name(for user: User) -> String?

// ❌
func getName(for user: User) -> String?
// ✅
func backButtonDidTap() {
  // ...
}

// ❌
func back() {
  // ...
}

// ❌
func pressBack() {
  // ...
}

변수

상수

열거형

약어

// ✅
let userID: Int?
let html: String?
let websiteURL: URL?
let urlString: String?

Delegate

// ✅ UserCell
protocol UserCellDelegate {
  func userCellDidSetProfileImage(_ cell: UserCell)
  func userCell(_ cell: UserCell, didTapFollowButtonWith user: User)
}

클로저

// ❌ let completionBlock: (() -> ())? let completionBlock: ((Void) -> (Void))?

- Closure 정의시 파라미터에는 괄호를 사용하지 않는다.
- Closure 정의시 가능한 경우 타입 정의를 생략한다.
- Closure 호출 시, 또 다른 유일한 Closure를 마지막 파라미터로 받는 경우, 파라미터 이름을 생략한다.

## 클래스와 구조체

- 클래스와 구조체 내부에서는 `self`를 명시적으로 사용한다.
- 구조체를 생성할 때에는 Swift구조체 생성자를 사용한다.

## 타입

- `Array<T>`와 `Dictionary<T: U>`보다는` [T]`, `[T: U]`를 사용한다.

## 주석

- `///`를 사용해서 문서화에 사용되는 주석을 남긴다.
```swift
/// 사용자 프로필을 그려주는 뷰
class ProfileView: UIView {
  var nameLabel: UILabel!
}

프로그래밍 권장사항

}

이렇게 선언된 상수들은 다음과 같이 사용될 수 있다.
```swift
self.profileImageView.frame.origin.x = Metric.profileImageViewLeft
self.nameLabel.font = Font.nameLabel
self.nameLabel.textColor = Color.nameLabelText