Skip to content

Commit

Permalink
refactor: improve
Browse files Browse the repository at this point in the history
  • Loading branch information
ShyngysSaktagan committed Nov 27, 2023
1 parent 5f06ea3 commit 97f3fd1
Showing 1 changed file with 32 additions and 11 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import io.outfoxx.swiftpoet.CodeBlock
import io.outfoxx.swiftpoet.EnumerationCaseSpec
import io.outfoxx.swiftpoet.FunctionSpec
import io.outfoxx.swiftpoet.Modifier
import io.outfoxx.swiftpoet.ParameterizedTypeName
import io.outfoxx.swiftpoet.PropertySpec
import io.outfoxx.swiftpoet.TypeName
import io.outfoxx.swiftpoet.TypeSpec
Expand Down Expand Up @@ -211,24 +212,44 @@ class SealedToSwiftEnumFeature(
returnType: TypeName
) {
val paramType: TypeName? = enumCase.param
val cast = "as?"
val cast: String
val returnedName: String

if (paramType == null) {
returnedName = "${enumCase.caseArg}()"
cast = if (returnType is ParameterizedTypeName) {
// The return type is generic and there is no parameter, so it can
// be assumed that the case is NOT generic. Thus the case needs to
// be force-cast.
"as!"
} else {
// The return type is NOT generic and there is no parameter, so a
// regular cast can be used.
"as"
}
} else {
// There is a parameter
returnedName = "obj"
cast = if (paramType is ParameterizedTypeName && returnType is ParameterizedTypeName) {
if (paramType.typeArguments == returnType.typeArguments) {
// The parameter and return type have the same generic pattern. This
// is true if both are NOT generic OR if both are generic. Thus a
// regular cast can be used.
"as"
} else {
"as!"
}
} else if (paramType !is ParameterizedTypeName && returnType !is ParameterizedTypeName) {
// If the parameter and return type is not ParameterizedTypeName
// regular cast can be used.
"as"
} else {
// If the parameter and return type have differing generic patterns
// then a force-cast is needed.
"as!"
}
}

add("if let sealedInstance = $returnedName $cast $returnType {\n")
indent()
add("return sealedInstance\n")
unindent()
add("} else {\n")
indent()
add("fatalError(\"Type mismatch in sealed property\")\n")
unindent()
add("}\n")
add("return $returnedName $cast $returnType\n")
}

data class EnumCase(
Expand Down

0 comments on commit 97f3fd1

Please sign in to comment.