왜 문자열로 숫자를 표현해야하는가?


정렬


Custom sort

let ints = ["1", "2", "23", "32", "999"]

ints.sorted { lhs, rhs in
  
  if lhs.count == rhs.count {
    
    for (lhc, rhc) in zip(lhs, rhs) {
      
      if Int(String(lhc))! == Int(String(rhc))! {
        continue
      } else {
        return Int(String(lhc))! < Int(String(rhc))!
      }
    }
    
    return true
    
  } else {
    return lhs.count < rhs.count
  }
}.forEach { print($0) }

0 표현


“00000000” 을 0 으로 표현해야할 때

  1. Int(str) - 타입 컨버전

    let str = "000000000000000000000000000000000000000000000"
    
    Int(str)
    
  2. allSatisfy 사용하기

    
    // given str = "00000000000000000"
    
    if str.allSatisfy({ $0 == "0" }) {
    	str = "0"
    }
    
    // str == "0"