import Foundation import VGSL extension [String: Function] { mutating func addGetValueFunctions() { addFunction("getBooleanValue", makeFunction() as FunctionBinary) addFunction("getColorValue", _getColorValue) addFunction("getIntegerValue", makeFunction() as FunctionBinary) addFunction("getNumberValue", makeFunction() as FunctionBinary) addFunction("getStringValue", makeFunction() as FunctionBinary) addFunction("getUrlValue", _getUrlValue) } } private let _getColorValue = OverloadedFunction( functions: [ makeFunction() as FunctionBinary, makeFunction { guard let color = Color.color(withHexString: $0) else { throw ExpressionError( "Failed to get Color from (\($0)). Unable to convert value to Color." ) } return color } as FunctionBinary, ] ) private let _getUrlValue = OverloadedFunction( functions: [ makeFunction() as FunctionBinary, makeFunction { guard let url = URL(string: $0) else { throw ExpressionError( "Failed to get URL from (\($0)). Unable to convert value to URL." ) } return url } as FunctionBinary, ] ) private func makeFunction() -> FunctionBinary { makeFunction { $0 } } private func makeFunction( transform: @escaping (U) throws -> T ) -> FunctionBinary { FunctionBinary { name, fallbackValue, context in guard let value = context.variableValueProvider(name) else { return try transform(fallbackValue) } let typpedValue: T? = value as? T if typpedValue == nil { DivKitLogger.warning("The type of the variable \(name) is not \(T.self)") } return try typpedValue ?? transform(fallbackValue) } }