How to Use Extension in Swift 5.5 Playground
by Alexandra Kropova from Mammoth Interactive
Are you getting an error “No such module UIKit” or similar? Or perhaps an error about an extension not being recognized in your Swift Playground? Read the solution in this post.
Want to learn more? Enroll in Complete Web & App Development with Machine Learning For All (125 Hours). Free in the Mammoth Unlimited Membership. Get 250+ courses and 2,000 hours at a dirt-cheap price.
An example where the problem occurs:
You build an extension that you are trying to use in a Swift Playground:
import UIKit extension UIImage { ... }
Error message:
No such module UIKit
or
The class UIImage does not have the function yourExtensionFunction
Solution
Swift Playgrounds can have trouble recognizing files in different folders because of how a Swift Playground is run/compiled. To enable the extension, put the extension directly in the Swift Playground file, instead of putting the extension in a separate file.
Still not working?
Other tips that may help include:
- Move the extension and the file where you use the extension into the same subfolder.
- Click on the top-level Playground file. Open Xcode’s right-hand sidebar. Make sure your target is iOS if you are using an iOS class like UIImage. Some classes are only available in iOS or macOS but not both.
Toolkit:
- Xcode 13
- Swift 5.5
- SwiftUI 3
- iOS 15
Suggest more solutions or ask a question in the comments below.
Want to learn more? Enroll in Complete Web & App Development with Machine Learning For All (125 Hours). Free in the Mammoth Unlimited Membership. Get 250+ courses and 2,000 hours at a dirt-cheap price.