Swift and SwiftUI Interoperability: A Practical Guide to Type Conversion

Experienced iOS and React Native Developer with 10+ Years of Expertise - Available for New Opportunities. Connect Now!
Search for a command to run...

Experienced iOS and React Native Developer with 10+ Years of Expertise - Available for New Opportunities. Connect Now!
No comments yet. Be the first to comment.
The use of protocols in Swift is integral to SwiftUI and leveraging these protocols is key to building flexible, reusable, and efficient SwiftUI applications. In this post, we will deep dive into eight essential protocols that every SwiftUI developer...
This time, I'm exploring the fascinating world of AI, stepping away from my usual focus on iOS development. There's so much more to share about AI, and I can't wait to dive into it with you! If you'd like to follow along and receive regular updates, ...

The app is Time Tango, a Pomodoro timer app. I chose this concept after conducting keyword research for popular terms that face minimal competition on the app store. The app is free to use and received approval in its first review. The strategy focus...

In my last article, I talked about how data flows in SwiftUI. Now, Apple has released something new in iOS 17 - the Observation Framework. This changes how SwiftUI works with data. In this article, we will look at how to use the new Observable Macro ...

One of the critical elements of SwiftUI is its approach to managing data flow within applications. This comprehensive guide will provide you with a strong understanding of data flow in SwiftUI, how it operates, and why it's vital for your SwiftUI app...

Arrays are one of the most common data structures used in programming. In Swift, arrays are used to store ordered lists of values of the same type. They are incredibly versatile and powerful, but using them efficiently is key to writing high-performi...

This post will guide you through the process of converting between Swift and SwiftUI types and vice versa. This ability is quite useful, especially when you have existing Swift code that you want to integrate with SwiftUI or need to use SwiftUI types in a Swift context.
In Swift, we use String to store and manage a sequence of characters. In SwiftUI, we use Text to display a static text label in your user interface. Here's how you convert a Swift String to a SwiftUI Text.
let swiftString: String = "Hello, SwiftUI!"
let swiftUIText: Text = Text(swiftString)
In Swift, we use UIColor to represent a color in an RGB color space. In SwiftUI, we use Color. Converting a UIColor to a Color is straightforward:
let swiftUIColor: UIColor = .red
let swiftUIColor = Color(swiftUIColor)
Swift uses UIImage for representing images, while SwiftUI uses Image. Here's how to convert a UIImage to an Image.
let uiImage: UIImage = UIImage(named: "example")!
let image = Image(uiImage: uiImage)
Swift uses UIButton for buttons, while SwiftUI uses Button. Here's how to convert a UIButton action to a SwiftUI Button.
In Swift:
let button = UIButton(type: .system)
button.setTitle("Click me", for: .normal)
button.addTarget(self, action: #selector(buttonClicked), for: .touchUpInside)
@objc func buttonClicked() {
print("Button clicked")
}
In SwiftUI:
Button(action: {
print("Button clicked")
}) {
Text("Click me")
}
It's important to note that SwiftUI's Text does not have a direct way to convert back to a String because Text in SwiftUI is not just a simple string; it's a view. It is designed to handle complex tasks like localization, style, and accessibility features. However, if you need to extract the string value for some reason, you could initially store it in a String variable before converting it to Text.
let swiftString: String = "Hello, Swift!"
let swiftUIText: Text = Text(swiftString)
// Use swiftString when you need the string value.
Similar to the Text to String conversion, SwiftUI's Color does not provide a built-in way to convert back to UIColor. This is because SwiftUI's Color is more complex; it's not just a simple color but a dynamic provider of colors, supporting the Dark Mode feature of iOS, for example.
However, you can use an extension to Color to get a UIColor:
import SwiftUI
import UIKit
extension Color {
func uiColor() -> UIColor {
if #available(iOS 14.0, *) {
return UIColor(self)
}
let scanner = Scanner(string: self.description.trimmingCharacters(in: CharacterSet.alphanumerics.inverted))
var hexNumber: UInt64 = 0
var r: CGFloat = 0.0, g: CGFloat = 0.0, b: CGFloat = 0.0
let result = scanner.scanHexInt64(&hexNumber)
if result {
r = CGFloat((hexNumber & 0xff000000) >> 24) / 255
g = CGFloat((hexNumber & 0x00ff0000) >> 16) / 255
b = CGFloat((hexNumber & 0x0000ff00) >> 8) / 255
}
return UIColor(red: r, green: g, blue: b, alpha: 1.0)
}
}
Now you can convert a Color to a UIColor like this:
let swiftUIColor = Color.red.uiColor()
This conversion process may not be perfect due to the complexity of the Color type, but it should suffice for most use cases.
Converting SwiftUI's Image back to UIKit's UIImage is not straightforward as SwiftUI's Image type doesn't provide a direct way to access the underlying UIImage. This is because Image in SwiftUI is a view, not a direct wrapper around an image like UIImage. If you need to convert a SwiftUI Image to a UIImage, you should keep the original UIImage you used to create the Image.
You might also like: SwiftUI Magic: 7 Lesser-Known Features That Will Make Your Apps Stand Out
In this post, we've discussed the conversion of Swift types to SwiftUI types and vice versa. While straightforward in some cases, it's important to remember that SwiftUI types are more complex and designed to handle a wider range of tasks, making direct conversion back to Swift types challenging in some cases. When necessary, workarounds and extensions can be employed to facilitate this process.
As SwiftUI continues to evolve, there may be changes and improvements that could affect this conversion process, so it's always a good idea to keep up-to-date with the latest SwiftUI documentation and community discussions.
I hope you enjoyed this article, and if you have any questions, comments, or feedback, then feel free to comment here or reach out via Twitter.
Thanks for reading!