iOS/iOS Swift 문법

String(describing: ) 사용 예시

Developer-Michelle 2023. 2. 9. 16:33

String(describing: ) 사용 예시

토이프로젝트 Compositional Layout 하다가...

extension MyCollectionViewController: UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return systemImageNameArray.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cellId = String(describing: MyCollectionViewCell.self)
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! MyCollectionViewCell
        
        cell.profileImg.image = UIImage(systemName: systemImageNameArray[indexPath.item])
        cell.profileLabel.text = systemImageNameArray[indexPath.item]
        
        return cell
    }
}

 

CollectionView cellForItemAt 에서 cellId 리터럴하게 계속해서 쓰는 것 방지.

즉, String(describing: ) 은 자기 자신을 출력 (아래의 경우 class 이름 자체가 출력)

let cellId = String(describing: MyCollectionViewCell.self)
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! MyCollectionViewCell

 

 let cellId = String(describing: MyCollectionViewCell.self)

 이렇게 쓰고

print(cellId를 출력해보면 다음과 같이 나온다)

MyCollectionViewCell