FlexLayout icon indicating copy to clipboard operation
FlexLayout copied to clipboard

CGFLoat casting boilerplate

Open Kuluum opened this issue 5 years ago • 1 comments

When we create let/var for some of FlexLayout properties we should explicit cast values to CGFloat e.g.

let height = isSmall ? CGFloat(100.0) : CGFloat(200.0)

view.flex.height(height)

It looks dirty and not Swift type friendly. The best case is that flex can handle (almost) any argument type without an explicit cast.

let height = isSmall ? 100.0 : 200.0
let width = isSmall ? 500 : 1000
let padding: UInt = isSmall ? 12 : 24

view.flex.height(height).width(width).padding(padding)

I don't have a good solution to this problem, but I have a so-so one.

For each method that takes CGFloat as a parameter add two more methods. e.g. height()

// The original one
@discardableResult
public func height(_ value: CGFloat?) -> Flex {
  yoga.height = valueOrAuto(value)
  return self
}

// For Int-like types (Int, UInt, Int8, etc)
@discardableResult
public func height<T: BinaryInteger>(_ value: T = 0) -> Flex {
  let cgValue = CGFloat(value)
  return height(cgValue)
}

// For float-like types (Double, Float, etc)
@discardableResult
public func height<T: BinaryFloatingPoint>(_ value: T?) -> Flex {
  let cgValue = CGFloat(value ?? 0.0)
  return height(cgValue)
}

I understand that this will lead to a lot of boilerplate inside Flex, but I believe it also makes Flex more usable.

If you have a better idea, I'm open to conversation.

If you OK with this solution, I can do all the stuff and make PR.

Kuluum avatar Dec 18 '20 17:12 Kuluum

Sorry for the late response. But yes, that would be a nice improvement for Swift

lucdion avatar Feb 23 '21 22:02 lucdion

Very old topic. Closing it, sorry

lucdion avatar Mar 01 '23 20:03 lucdion