Swift is a general-purpose, multi-paradigm language developed for Apple Ecosystem by Apple Inc. and the open-source community. It also uses modern safety, performance, and software design patterns.

Popular New Releases in Swift

Alamofire

Missing Cancellation Parameter

open-source-ios-apps

3.2.0

iina

IINA 1.2.0

Charts

v4.0.2 Release

lottie-ios

3.3.0

Popular Libraries in Swift

awesome-ios

by vsouza doticonswiftdoticon

star image 37808 doticonMIT

A curated list of awesome iOS ecosystem, including Objective-C and Swift Projects

Alamofire

by Alamofire doticonswiftdoticon

star image 37489 doticonMIT

Elegant HTTP Networking in Swift

open-source-ios-apps

by dkhamsing doticonswiftdoticon

star image 29606 doticonCC0-1.0

:iphone: Collaborative List of Open-Source iOS Apps

ShadowsocksX-NG

by shadowsocks doticonswiftdoticon

star image 29570 doticonGPL-3.0

Next Generation of ShadowsocksX

open-source-mac-os-apps

by serhii-londar doticonswiftdoticon

star image 28479 doticonCC0-1.0

🚀 Awesome list of open source applications for macOS. https://t.me/s/opensourcemacosapps

iina

by iina doticonswiftdoticon

star image 27842 doticonGPL-3.0

The modern video player for macOS.

swift-algorithm-club

by raywenderlich doticonswiftdoticon

star image 25240 doticonMIT

Algorithms and data structures in Swift, with explanations!

Charts

by danielgindi doticonswiftdoticon

star image 25068 doticonApache-2.0

Beautiful charts for iOS/tvOS/OSX! The Apple side of the crossplatform MPAndroidChart.

lottie-ios

by airbnb doticonswiftdoticon

star image 22558 doticonApache-2.0

An iOS library to natively render After Effects vector animations

Trending New libraries in Swift

CodeEdit

by CodeEditApp doticonswiftdoticon

star image 7360 doticonMIT

CodeEdit App for macOS – Elevate your code editing experience. Open source, free forever.

eul

by gao-sun doticonswiftdoticon

star image 6929 doticonMIT

🖥️ macOS status monitoring app written in SwiftUI.

swift-composable-architecture

by pointfreeco doticonswiftdoticon

star image 5888 doticonMIT

A library for building applications in a consistent and understandable way, with composition, testing, and ergonomics in mind.

ControlRoom

by twostraws doticonswiftdoticon

star image 4440 doticonMIT

A macOS app to control the Xcode Simulator.

DevToysMac

by ObuchiYuki doticonswiftdoticon

star image 4379 doticonMIT

DevToys For mac

AlDente

by davidwernhart doticonswiftdoticon

star image 4373 doticonNOASSERTION

macOS tool to limit maximum charging percentage

swift-algorithms

by apple doticonswiftdoticon

star image 4179 doticonApache-2.0

Commonly used sequence and collection algorithms for Swift

secretive

by maxgoedjen doticonswiftdoticon

star image 4030 doticonMIT

Store SSH keys in the Secure Enclave

Pulse

by kean doticonswiftdoticon

star image 3994 doticonMIT

Logger and network inspector for Apple platforms

Top Authors in Swift

1

learn-co-curriculum

181 Libraries

star icon89

2

objcio

181 Libraries

star icon6089

3

mohsinalimat

162 Libraries

star icon215

4

appcoda

134 Libraries

star icon3375

5

ahmetbostanciklioglu

115 Libraries

star icon0

6

ram4ik

108 Libraries

star icon92

7

nyannya0328

106 Libraries

star icon0

8

vapor-community

100 Libraries

star icon3285

9

FlexMonkey

99 Libraries

star icon7672

10

alfianlosari

93 Libraries

star icon2085

1

181 Libraries

star icon89

2

181 Libraries

star icon6089

3

162 Libraries

star icon215

4

134 Libraries

star icon3375

5

115 Libraries

star icon0

6

108 Libraries

star icon92

7

106 Libraries

star icon0

8

100 Libraries

star icon3285

9

99 Libraries

star icon7672

10

93 Libraries

star icon2085

Trending Kits in Swift

Here is a list of the best Swift/iOS animation libraries for 2023 that developers can use to create immersive animations for mobile app development.


Animations can make a huge difference in user experience. Animation Libraries are a great way to add dynamic animations to the app. Correctly implemented, functional, beautiful animations are a joy for users and will help keep them engaged in the app. These libraries cover everything from user interface design to app analytics in a way that makes it very easy to implement animation in projects.


We have curated a list of the ten best Swift/iOS animation libraries that each provide a unique function.

Lottie-web 

  • Useful in adding animated icons and illustrations.
  • Helps load animations.
  • Helps in animated backgrounds.

react-motion 

  • Allows beautiful animations and transitions with a simple syntax.
  • Customizes the timing and duration of animations.
  • Helps in creating complex animations and transitions with ease.

Hero 

  • Helpful in custom navigation transitions.
  • Helps in creating interactive animations when tapping on views.
  • Helps in creating personalized presentation transitions.

SkeletonView 

  • Represents the structure of the UI.
  • Helps in customizing the look of the skeleton screens.
  • Creates empty screen animations.

ViewAnimator

  • Helps in animating views with ease.
  • Allows customizable animations with different directions, delays, and durations.
  • Helps in combining multiple animations for complex effects.

SwiftMessages

  • Allows custom in-app notifications to come up with animations.
  • Allows customizable designs for alerts and banners.
  • Shows toast notifications.

LiquidLoader.

  • Creates a Fun, liquid-style loading animation.
  • Allows customizable animations with different colors and shapes.
  • Helps in modifying loading animations for buttons and UI elements.

AnimatedCollectionViewLayout 

  • Customizes the animation style and direction.
  • Helps in supporting different types of cells.
  • Creates 3D effects.

LNZCollectionLayouts 

  • Has custom collection view layouts for unique designs.
  • Allows supporting different layout styles, such as circular and spiral.
  • Provides dynamic resizing and animation of cells.

Shimmer

  • Helpful in table view and collection view loading animations.
  • Used for empty screen placeholder animations.
  • Mimics the look of reflective surfaces.

Here are some famous Swift Webserver Libraries. Swift Webserver Libraries use cases include Building a custom web server, Creating a content delivery network (CDN), Hosting a web application, and Developing a mobile application backend.


Swift web server libraries are libraries that are designed to enable developers to create web applications using the Swift programming language. These libraries provide tools to help developers with server-side development tasks such as routing, templating, and data handling.


Let us look at these libraries in detial.

vapor

  • Provides a type-safe, declarative framework for writing web applications.
  • Built-in support for asynchronous programming.
  • Offers an integrated authentication and authorization system.

Moya

  • Supports advanced authentication methods, such as OAuth2, Basic Auth, Client Certificate Authentication and Bearer Tokens.
  • Provides an easy way to mock network requests for testing and development.
  • Allows for custom header, query, and request body encoding for each request.

Perfect

  • Provides a scalable, high-performance web server that is optimized for Swift applications.
  • Offers built-in support for TemplateKit, a powerful templating engine for producing dynamic web content.
  • Has a robust set of development tools and libraries, including an integrated debugger and profiler.

Kitura

  • Built with a modular architecture that supports pluggable components to customize the server’s functionality.
  • Kitura-Stencil template engine allows you to write HTML templates in Swift, making it easier to create dynamic webpages.
  • Supports cloud deployment, allowing you to easily deploy your applications to the cloud.

swifter

  • Built-in security features such as TLS encryption and sandboxing.
  • Designed to be easy to setup and get up and running quickly.
  • Highly extensible and allows developers to customize the server to their own needs.

Zewo

  • Built with an asynchronous, non-blocking I/O model.
  • Optimized for both OS X and Linux and is fully compatible with Swift Package Manager.
  • Built-in support for HTTP/2, TLS/SSL, and other security features.

blackfire

  • Provides support for both synchronous and asynchronous requests.
  • Offers a range of deployment options, including Docker and Kubernetes.
  • Built-in support for the most popular web development frameworks, such as Laravel, Symfony, and Express.

Kitura-NIO

  • Makes it easy to define routes and map them to specific functions.
  • Uses non-blocking I/O operations.
  • Provides native support for secure communication over TLS.

Here are some of the famous Swift XML Libraries. The use cases of these libraries include: 

  • Parsing XML data into objects. 
  • Generating XML documents. 
  • Validating XML documents. 
  • Transforming XML documents. 
  • Querying XML documents.  


Swift XML libraries allow developers to work with XML data in the Swift programming language. Some popular Swift XML libraries include XMLCoder, SwiftSoup, and AEXML. These libraries may provide classes and methods to parse, serialize, and traverse XML documents and methods to create and manipulate XML documents.   


Let us look at some of these famous libraries. 

SwiftSoup

  • Offers a full-featured API for navigating and manipulating HTML documents.
  • Supports a variety of HTML5 elements and attributes.
  • Has a robust test suite that ensures the accuracy and correctness of the library.

BonMot

  • Offers integrated support for internationalization and localization.
  • Allows for custom styling and formatting of strings
  • Offers an easy-to-use templating engine, allowing developers to quickly and easily create complex XML documents.

SwiftRichString

  • Supports multiple output formats, including JSON, HTML, and plain text.
  • Supports both attribute- and element-level parsing, giving developers the flexibility to choose the level of detail they need.
  • Allows developers to customize the parsing process easily, giving them full control over the output. 

Kanna

  • Supports both DOM and SAX parsing.
  • Offers extensive error checking and debugging options.
  • Enables efficient searching and filtering of XML documents.

Plot

  • Features a powerful styling system that allows developers to quickly style their layouts with just a few lines of code.  
  • Supports custom node types, allowing developers to create custom nodes and use them in layouts.  
  • Provides a built-in animation system that can easily animate UI changes. 

SwiftSVG

  • Is an open-source library and is actively maintained, making it easier to keep up with the latest features and changes.
  • Is optimized for performance and scalability, making it suitable for large-scale projects.
  • Can generate SVG documents from scratch, making it easier to create complex visuals.

SWXMLHash

  • Supports namespace prefixes for easy lookup of elements.
  • Allows developers to extract values from XML documents.
  • Allows developers to for specific tags, attributes and values.

Fuzi

  • Is designed to be memory efficient, allowing the user to process large XML documents without too much memory.  
  • Uses lazy loading and caching to ensure fast and efficient parsing of XML documents.  
  • Offers comprehensive documentation, tutorials, and examples to help the user get started quickly. 

AEXML

  • Provides a functional programming interface for transforming XML documents.
  • Supports both Objective-C and Swift code.
  • Provides an easy way to convert XML documents to JSON and vice versa.

EVReflection

  • An intuitive dot syntax for accessing and setting properties in an XML document is included.   
  • Support for multiple data types, including objects, arrays, and dictionaries. 
  • Is written in pure Swift, making it easy to integrate into existing Swift projects. 

Here are some of the famous Swift Socket Libraries. The use cases of these libraries include Developing Custom Network Applications, Developing Server-Side Applications, Developing Streaming Applications, Developing Peer-to-Peer Applications, and Developing Distributed Applications. 


Swift Socket Libraries are libraries written in the Swift language that provide an interface for applications to communicate over a network. These libraries allow developers to create custom networking applications that are capable of sending and receiving data over the internet. They provide an easy-to-use interface for developers to create powerful applications that can interact with other computers, servers, and services.


Let us look at some of these famous libraries. 

Staescream

  • Supports WebSocket compression, which reduces the amount of data sent over the wire.
  • Provides methods to read and write data to the socket connection easily. 
  • Supports both TCP and UDP connections.

swift-nio

  • Provides a non-blocking IO model, allowing high scalability and performance.  
  • Supports many protocols, including HTTP, HTTPS, WebSockets, and more.  
  • Supports reactive programming, allowing developers to write asynchronous code more efficiently

SwiftSocket

  • Supports IPv4 and IPv6, as well as TLS/SSL encryption.
  • Provides a well-documented API, making it easy to integrate into your existing Swift projects.
  • Supports multiple platforms including iOS, macOS, tvOS, and watchOS.

SwiftWebSocket

  • Provides a fast and lightweight WebSocket client written in Swift.
  • Provides real-time diagnostics and debugging features, including logging and message tracing.
  • Provides full control over message headers and payloads.

BlueSocket

  • Highly customizable, it allows developers to customize the features of their network protocols and sockets.
  • Implements all the latest security protocols, such as TLS 1.3 and WebSockets, to protect users' data.
  • Has built-in support for IPv6, allowing developers to create applications easily. 

sockets

  • Provides a flexible way to configure socket options.
  • Provides secure communication between client and server with encryption and authentication.
  • Provides high performance and low latency for data transfers.

JustLog

  • Offers a unique feature called "context switching," which allows developers to switch between different networks while their application runs. 
  • Provides an efficient asynchronous architecture which makes it easy to manage multiple connections. 
  • Supports real-time data synchronization with the help of an efficient and reliable protocol. 


Here are the best open-source iOS calendar libraries for your applications. You can use these software development tools to integrate calendar functionality into their iOS applications easily.

 

There are several popular iOS Calendar Libraries available. These libraries provide a set of pre-built features that can be used to create custom calendar views, manage events and schedules, and synchronize data with the built-in iOS calendar app. These libraries provide a set of pre-built features that can be used to create custom calendar views, manage events and schedules, and synchronize data with the built-in iOS calendar app. Also, certain customizable calendar libraries offer a range of features, including support for Gregorian and Lunar calendars, event management, and animated transitions. It also provides a range of UI customization options, including custom colors, fonts, and header styles. Besides, you can use the built-in iOS framework to access the device's calendar and reminders. They allow developers to create, read, update, and delete events and reminders and respond to calendar and reminder notifications.

 

Overall, iOS Calendar Libraries provide developers with an efficient and customizable way to add calendar functionality to their iOS applications. By choosing the right library and leveraging its features, developers can create sophisticated calendar views and management tools that enhance the user experience of their applications. We have handpicked the top and trending open-source iOS calendar libraries for your next application development project.

EventKit:

  • Used in Mobile, iOS applications, etc.
  • This built-in iOS framework provides access to the device's calendar and reminders.
  • Allows to create, read, update, and delete events and reminders.

HorizonCalendar:

  • Used in Mobile, iOS, React applications, etc.
  • Allows displaying a range of dates in a vertical scrolling or horizontal scrolling calendar component.
  • Provides various customization points with support for a wide range of designs and use cases.

CalendarView:

  • Used in User Interface, Calendar applications, etc.
  • Provides "just drag and drop it in your code" calendar functionality for iOS.
  • Supports both vertical and horizontal scrolling, along with native calendar events.

JTAppleCalendar:

  • Used in User Interface, Calendar, React Native applications, etc.
  • Provides various customization options and features.
  • Supports different calendar types, event management, and custom date cells.

CVCalendar:

  • Used in User Interface, Calendar applications, etc.
  • Features include different calendar types, event management, and animated transitions.
  • Supports iOS 8+ and Swift (>= 4.0).

Swift-Calendar:

  • Used in User Interface, Calendar, Xcode applications, etc.
  • Provides a customizable calendar view with a range of UI customization options.
  • Supports different calendar types, event management, etc.

JZCalendarWeekView:

  • Used in User Interface, iOS Calendar applications, etc.
  • Offers iOS Calendar Week/Day View in Swift.
  • Provides support for event management and UI customization options.

CalendarKit:

  • Used to create iOS Calendar App in Swift.
  • Supports different calendar types and event management, calendar views, and management tools.
  • It looks like the Apple Calendar app out-of-the-box, with various UI customization options.

Here are the best open-source iOS slider libraries for your applications. You can use these pre-built components for creating slider controls in their iOS apps to enhance the user experience of their applications.

 

A slider is a UI component that allows users to select a value by dragging a thumb along a track. This UI element is commonly used in many iOS apps, such as music players, photo editors, and fitness apps, to name a few. The iOS Slider Libraries provide developers with various customizable slider controls that they can easily integrate into their apps. These libraries typically come with features such as customizing the slider’s appearance, setting the minimum and maximum values, defining the step interval, and enabling or disabling user interaction. These libraries offer developers a quick and efficient way to add slider controls to their apps without creating them from scratch. They are designed to be easy to use and highly customizable, allowing developers to tailor them to their app's needs.

 

Overall, the iOS Slider Libraries are a valuable resource for developers looking to enhance their app user experience by adding slider controls. With a wide range of options, developers can choose the library that best suits their app requirements and implement it in minutes. We have handpicked the top and trending open-source iOS slider libraries for your next application development project.

RangeSlider:

  • Used for creating range sliders in User Interface, Animation, iOS applications, etc.
  • Allows users to select a range of values between a minimum and maximum.
  • Offers customization options for changes to the slider's appearance and behavior.

CircularSlider:

  • Used in Mobile, iOS, Xcode applications, etc.
  • Provides a circular slider that can be used to create unique and engaging interfaces.
  • Also, it can be customized with colors, text, and icons.

Fluid Slider:

  • Used for creating fluid sliders with smooth thumb transitions between values as the user drags it.
  • Supports both horizontal and vertical sliders.
  • Allows for customization of the slider's appearance.

SwiftUI-sliders:

  • Used in User Interface, Frontend Framework, Xcode applications, etc.
  • Allows building highly customizable sliders and tracks.
  • Provides different sizes for lower and upper-range thumbs.

RangeSeekSlider:

  • Used in Mobile, iOS, Xcode, Uikit applications, etc.
  • Provides a range slider like TTRangeSlider.
  • Additional features include customizable labels and setting a pre-selected range.

AORangeSlider:

  • Used in User Interface, Animation, iOS applications, etc.
  • Provides two handlers to pick a minimum and a maximum range.
  • It also allows for customization of the label's appearance.

AIFlatSwitch:

  • Used in Mobile, iOS, Uikit applications, etc.
  • Adding multiple positions provides a switch control that can be used as a slider. 
  • Supports customization of the switch's appearance.

GradientSlider:

  • Used for creating sliders with color picker functionality in iOS applications.
  • Provides a slider with a gradient background.
  • Can be customized with different colors and gradients.

Here are the best open-source iOS menu libraries for your applications. You can use these collections of software tools to create dynamic, responsive, and custom menu interfaces for iOS applications.


iOS Menu Libraries allow developers to create menu interfaces that are not only functional but also aesthetically pleasing and intuitive. These libraries provide developers with pre-built components, animations, and templates to simplify the menu interface creation process. The libraries are designed to work seamlessly with iOS, so they integrate well with the operating system and other iOS components. They offer different menu styles, such as drop-down, slide-out, and pop-up menus. Also, developers can customize the menu's appearance, including colors, fonts, and icons, to match their app's design. One of the primary benefits of using iOS Menu Libraries is that they can help developers create visually appealing and user-friendly menus. Using pre-built components, developers can quickly prototype and refine menu designs based on user feedback. This allows developers to iterate quickly and deliver high-quality menu interfaces that meet the needs of their users. Another advantage of using iOS Menu Libraries is that developers can focus on customizing the menus to fit their app's unique needs. This can significantly reduce development time and free up resources for other tasks.


We have handpicked the top and trending open-source iOS menu libraries for your next application development project. IOS Menu Libraries allow developers to create custom menu interfaces that enhance their app's usability and user experience. With various features and styles available, developers can choose the library that best suits their app's requirements and implement it in minutes.

SideMenu:

  • Used to create a simple and versatile side menu control in Swift for iOS devices.
  • It’s a popular open-source menu library that offers a customizable side menu interface.
  • Supports multiple menu items and provides various animation effects for menu transitions.

RadialMenu:

  • Used in Mobile, iOS applications, etc.
  • Allows developers to create circular menus.
  • Offers various customization options and supports both touch and swipe gestures.

EZSwipeController:

  • Used to create a swipeable tab interface for menus.
  • Supports horizontal and vertical swipe gestures.
  • Offers customization options for animation effects.

Dropdowns:

  • Used to build dropdown interface for menus in iOS.
  • It’s a simple, lightweight menu library supporting single and multi-select dropdowns.
  • Offers customization options for dropdown appearance.

PageMenu:

  • Used for building a paging menu interface in Swift for iOS devices.
  • Allows developers to create multiple pages.
  • Supports customization options for page appearance and animation effects.

BubbleTransition:

  • Used to create a bubble-like interface for menu transitions.
  • Supports both zoom and fade effects.
  • Offers customization options for bubble size and color.

GuillotineMenu:

  • Used in User Interface, Animation, iOS applications, etc.
  • Provides a unique and customizable menu interface.
  • Offers a vertical slide-out menu with a guillotine-style animation effect.

YNDropDownMenu:

  • Used to create e customizable dropdown menu interface.
  • Supports both single and multi-select dropdowns.
  • Offers customization options for dropdown appearance and animation effects.

ENSwiftSideMenu:

  • Used in User Interface, Menu, Uikit, iOS applications, etc.
  • Offers a lightweight flyover side menu component for iOS.
  • Features include UIDynamic's bouncing animation, UIGestures, and UIBlurEffect.

Trending Discussions on Swift

UIButton with custom image still shows titleLabel even though I set it to blank - Swift iOS

Swift Concurrency announced for iOS 13 in Xcode 13.2 - how did they achieve this?

Xcode Playground Failed to launch

What's the library should I import for UTTypeImage, which is the replacement of kUTTypeImage in iOS 15?

Xcode 13 instruments is not a developer tool or in PATH (React native)

How to prevent actor reentrancy resulting in duplicative requests?

Cancelling an async/await Network Request

What are the differences between xcodebuild, xcrun and swift command line tools?

Xcode 13.2 - Adding package hangs on "Preparing to validate"

Xcode 13.2 - Internal error : Missing Package Description Module

QUESTION

UIButton with custom image still shows titleLabel even though I set it to blank - Swift iOS

Asked 2022-Mar-18 at 16:53

I'm pretty new to Swift, currently writing an AR game. Seems like my issue is very basic, but I can't figure it out.

I added a button to an AR Scene through the storyboard and linked it to an IBAction function (which works correctly when the button is clicked). I gave the button an image and deleted the Title. See how the button shows up in the storyboard: button in Xcode storyboard without Title

But when I run the app, the button image shows up with a default label (saying "Button") as shown in this image: button in iPhone screenshot WITH label next to the button image

I can't figure out why this label is there and how to remove it. Should I add the button programmatically instead of adding it through the storyboard? Should the button be treated differently because it's an AR app?

I was able to remove the label by adding the same UIButton as an IBOutlet and adding the following line in viewWillAppear:

1restartButton.titleLabel?.text = ""
2

But this feels to me like a workaround and not a real solution. Also, as soon as I click on the button, the label shows up again. I tried to add the same workaround line to the function when the button is clicked, but that didn't help.

I'm sure I'm missing something very simple. Your help would be appreciated.

Thanks!

ANSWER

Answered 2021-Nov-23 at 21:07

When Interface Builder isn't playing nice, I often open the Storyboard file in a text editor (I use Sublime Text) and edit it manually.

I had a similar issue - I had a button with an image, I had deleted the default "Button" title text in IB, which looked fine in Xcode, but when I ran it, the word "Button" was still there. So I found this line using Sublime Text and deleted it there:

1restartButton.titleLabel?.text = ""
2<state key="normal" title="Button"/>
3

After that, it worked correctly.

Source https://stackoverflow.com/questions/69980698

QUESTION

Swift Concurrency announced for iOS 13 in Xcode 13.2 - how did they achieve this?

Asked 2022-Mar-11 at 12:26

Xcode 13.2 Beta release notes features a promise for Swift Concurrency support for iOS 13.

You can now use Swift Concurrency in applications that deploy to macOS 10.15, iOS 13, tvOS 13, and watchOS 6 or newer. This support includes async/await, actors, global actors, structured concurrency, and the task APIs. (70738378)

However, back in Summer 2021 when it first appeared at WWDC it was hard constrained to be run on iOS 15+ only.

My question is: what changed? How did they achieve backwards compatibility? Does it run in any way that is drastically different from the way it would run in iOS 15?

ANSWER

Answered 2021-Oct-28 at 14:06

Back-deploying concurrency to older OS versions bundles a concurrency runtime library along with your app with the support required for this feature, much like Swift used to do with the standard library prior to ABI stability in Swift 5, when Swift could be shipped with the OS.

This bundles parts of the Concurrency portions of the standard library (stable link) along with some additional support and stubs for functionality (stable link).

This bundling isn't necessary when deploying to OS versions new enough to contain these runtime features as part of the OS.


Since the feature on iOS 15+ (and associated OS releases) was stated to require kernel changes (for the new cooperative threading model) which themselves cannot be backported, the implementation of certain features includes shims based on existing functionality which does exist on those OSes, but which might perform a little bit differently, or less efficiently.

You can see this in a few places in Doug Gregor's PR for backporting concurrency — in a few places, checks for SWIFT_CONCURRENCY_BACK_DEPLOYMENT change the implementation where some assumptions no longer hold, or functionality isn't present. For example, the GlobalExecutor can't make assumptions about dispatch_get_global_queue being cooperative (because that threading model doesn't exist on older OSes), so when backporting, it has to create its own queue for use as the global cooperative queue. @objc-based actors also need to have their superclass swizzled, which doesn't need to happen on non-backdeployed runtimes. (Symbols also have to be injected in some places into the backdeploy libs, and certain behaviors have to be stubbed out, but that's a bit less interesting.)

Overall, there isn't comprehensive documentation on the exact differences between backdeploying and not (short of reading all of the code), but it should be safe to assume that the effective behavior of the backdeployed lib will be the same, though potentially at the cost of performance.

Source https://stackoverflow.com/questions/69746388

QUESTION

Xcode Playground Failed to launch

Asked 2022-Feb-27 at 21:27

I can't run any Xcode Swift Playground project without getting the error:

Failed to launch process. Failed to attach to stub for playground execution: error: attach failed ((os/kern) invalid argument)

Does anyone know how to solve this?

ANSWER

Answered 2021-Nov-11 at 09:56

I've the same issue. If I launch Xcode using rosetta, it doesn't show anything. You must switch off rosetta and it works perfect.

Source https://stackoverflow.com/questions/69829731

QUESTION

What's the library should I import for UTTypeImage, which is the replacement of kUTTypeImage in iOS 15?

Asked 2022-Feb-20 at 12:20

Before iOS 15, I used UIImagePickerController to capture images and video, and I got mediaType from [UIImagePickerController.InfoKey : Any], then I used kUTTypeImage (in the MobileCoreServices library) to identify the mediaType.

However, When it comes to iOS 15, Xcode complains that kUTTypeImage was deprecated in iOS 15.0. Use UTTypeImage instead. So, I replaced kUTTypeImage with UTTypeImage, but Xcode didn't know it.

Tried searching for some information, but didn't get any clue. I guess I should import the right library, but what is it?

Here is part of the code:

1func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
2        guard let mediaType = info[.mediaType] as? String else { return }
3        switch mediaType {
4        case String(kUTTypeImage):
5        // blabla
6        case String(kUTTypeMovie):
7        // blabla
8

and here are some screenshots: enter image description here

enter image description here

ANSWER

Answered 2021-Sep-26 at 06:40

It's a bit confusing. First, you'll need to import UniformTypeIdentifiers. Then, replace kUTTypeImage with UTType.image (the Swift version of UTTypeImage).

Source https://stackoverflow.com/questions/69332404

QUESTION

Xcode 13 instruments is not a developer tool or in PATH (React native)

Asked 2022-Feb-04 at 13:20

I recently upgraded to xcode13, before which react native app was working fine for long time. However, after switching when I run in iOS, I am getting error "instruments is not a developer tool or in PATH" on command "xcrun instruments". I tried following commands (all with Xcode in quit status)

1sudo xcode-select -r
2 
3

it reset the xcode select path to

1sudo xcode-select -r
2 
3 /Applications/Xcode.app/Contents/Developer
4

then I quit command line reopened and tried
xcrun instruments got same error again, so tried switching

1sudo xcode-select -r
2 
3 /Applications/Xcode.app/Contents/Developer
4 sudo xcode-select -s /Library/Developer/CommandLineTools
5

quit command line and tried again, still no success. each time i verified path change using command

1sudo xcode-select -r
2 
3 /Applications/Xcode.app/Contents/Developer
4 sudo xcode-select -s /Library/Developer/CommandLineTools
5  sudo xcode-select -p
6

I opened instruments app using cmd+space and could see version as 13, same as Xcode. That means matching instruments app(tool) exists but somehow xcrun is unable to find it which results in build failure.

FYI my react native version is 0.64.0. I saw couple of solutions like comment out flipper (which was not in my pod file though!) and add swift to library path in project.pbxproj, both solutions could not be applied.

Any suggestions would help.

ANSWER

Answered 2021-Sep-29 at 15:24

I've been getting the same error no matter what I've tried. I think there might be an error on setting the command line tools path with the Xcode version 13. So deleting XCode 13 (How to uninstall XCode) and reinstalling 12.5.1.(XCode12.5.1) solved the problem for me temporarily.

Source https://stackoverflow.com/questions/69314514

QUESTION

How to prevent actor reentrancy resulting in duplicative requests?

Asked 2022-Jan-21 at 06:56

In WWDC 2021 video, Protect mutable state with Swift actors, they provide the following code snippet:

1actor ImageDownloader {
2    private var cache: [URL: Image] = [:]
3
4    func image(from url: URL) async throws -> Image? {
5        if let cached = cache[url] {
6            return cached
7        }
8
9        let image = try await downloadImage(from: url)
10
11        cache[url] = cache[url, default: image]
12
13        return cache[url]
14    }
15
16    func downloadImage(from url: URL) async throws -> Image { ... }
17}
18

The issue is that actors offer reentrancy, so cache[url, default: image] reference effectively ensures that even if you performed a duplicative request because of some race, that you at least check the actor’s cache after the continuation, ensuring that you get the same image for the duplicative request.

And in that video, they say:

A better solution would be to avoid redundant downloads entirely. We’ve put that solution in the code associated with this video.

But there is no code associated with that video on the website. So, what is the better solution?

I understand the benefits of actor reentrancy (as discussed in SE-0306). E.g., if downloading four images, one does not want to prohibit reentrancy, losing concurrency of downloads. We would, effectively, like to wait for the result of a duplicative prior request for a particular image if any, and if not, start a new downloadImage.

ANSWER

Answered 2022-Jan-05 at 00:30

The key is to keep a reference to the Task, and if found, await its value.

Perhaps:

1actor ImageDownloader {
2    private var cache: [URL: Image] = [:]
3
4    func image(from url: URL) async throws -> Image? {
5        if let cached = cache[url] {
6            return cached
7        }
8
9        let image = try await downloadImage(from: url)
10
11        cache[url] = cache[url, default: image]
12
13        return cache[url]
14    }
15
16    func downloadImage(from url: URL) async throws -> Image { ... }
17}
18actor ImageDownloader {
19    private var cache: [URL: Image] = [:]
20    private var tasks: [URL: Task<Image, Error>] = [:]
21
22    func image(from url: URL) async throws -> Image {
23        if let image = try await tasks[url]?.value {
24            print("found request")
25            return image
26        }
27
28        if let cached = cache[url] {
29            print("found cached")
30            return cached
31        }
32
33        let task = Task {
34            try await download(from: url)
35        }
36
37        tasks[url] = task
38        defer { tasks[url] = nil }
39
40        let image = try await task.value
41        cache[url] = image
42
43        return image
44    }
45
46    private func download(from url: URL) async throws -> Image {
47        let (data, response) = try await URLSession.shared.data(from: url)
48        guard
49            let response = response as? HTTPURLResponse,
50            200 ..< 300 ~= response.statusCode,
51            let image = Image(data: data)
52        else {
53            throw URLError(.badServerResponse)
54        }
55        return image
56    }
57}
58

Source https://stackoverflow.com/questions/70586562

QUESTION

Cancelling an async/await Network Request

Asked 2022-Jan-03 at 22:23

I have a networking layer that currently uses completion handlers to deliver a result on the operation is complete.

As I support a number of iOS versions, I instead extend the network layer within the app to provide support for Combine. I'd like to extend this to now also a support Async/Await but I am struggling to understand how I can achieve this in a way that allows me to cancel requests.

The basic implementation looks like;

1
2protocol HTTPClientTask {
3    func cancel()
4}
5
6protocol HTTPClient {
7    typealias Result = Swift.Result<(data: Data, response: HTTPURLResponse), Error>
8    @discardableResult
9    func dispatch(_ request: URLRequest, completion: @escaping (Result) -> Void) -> HTTPClientTask
10}
11
12final class URLSessionHTTPClient: HTTPClient {
13    
14    private let session: URLSession
15    
16    init(session: URLSession) {
17        self.session = session
18    }
19    
20    func dispatch(_ request: URLRequest, completion: @escaping (HTTPClient.Result) -> Void) -> HTTPClientTask {
21        let task = session.dataTask(with: request) { data, response, error in
22            completion(Result {
23                if let error = error {
24                    throw error
25                } else if let data = data, let response = response as? HTTPURLResponse {
26                    return (data, response)
27                } else {
28                    throw UnexpectedValuesRepresentation()
29                }
30            })
31        }
32        task.resume()
33        return URLSessionTaskWrapper(wrapped: task)
34    }
35}
36
37private extension URLSessionHTTPClient {
38    struct UnexpectedValuesRepresentation: Error {}
39    
40    struct URLSessionTaskWrapper: HTTPClientTask {
41        let wrapped: URLSessionTask
42        
43        func cancel() {
44            wrapped.cancel()
45        }
46    }
47}
48

It very simply provides an abstraction that allows me to inject a URLSession instance.

By returning HTTPClientTask I can call cancel from a client and end the request.

I extend this in a client app using Combine as follows;

1
2protocol HTTPClientTask {
3    func cancel()
4}
5
6protocol HTTPClient {
7    typealias Result = Swift.Result<(data: Data, response: HTTPURLResponse), Error>
8    @discardableResult
9    func dispatch(_ request: URLRequest, completion: @escaping (Result) -> Void) -> HTTPClientTask
10}
11
12final class URLSessionHTTPClient: HTTPClient {
13    
14    private let session: URLSession
15    
16    init(session: URLSession) {
17        self.session = session
18    }
19    
20    func dispatch(_ request: URLRequest, completion: @escaping (HTTPClient.Result) -> Void) -> HTTPClientTask {
21        let task = session.dataTask(with: request) { data, response, error in
22            completion(Result {
23                if let error = error {
24                    throw error
25                } else if let data = data, let response = response as? HTTPURLResponse {
26                    return (data, response)
27                } else {
28                    throw UnexpectedValuesRepresentation()
29                }
30            })
31        }
32        task.resume()
33        return URLSessionTaskWrapper(wrapped: task)
34    }
35}
36
37private extension URLSessionHTTPClient {
38    struct UnexpectedValuesRepresentation: Error {}
39    
40    struct URLSessionTaskWrapper: HTTPClientTask {
41        let wrapped: URLSessionTask
42        
43        func cancel() {
44            wrapped.cancel()
45        }
46    }
47}
48extension HTTPClient {
49    typealias Publisher = AnyPublisher<(data: Data, response: HTTPURLResponse), Error>
50
51    func dispatchPublisher(for request: URLRequest) -> Publisher {
52        var task: HTTPClientTask?
53
54        return Deferred {
55            Future { completion in
56                task = self.dispatch(request, completion: completion)
57            }
58        }
59        .handleEvents(receiveCancel: { task?.cancel() })
60        .eraseToAnyPublisher()
61    }
62}
63

As you can see I now have an interface that supports canceling tasks.

Using async/await however, I am unsure what this should look like, how I can provide a mechanism for canceling requests.

My current attempt is;

1
2protocol HTTPClientTask {
3    func cancel()
4}
5
6protocol HTTPClient {
7    typealias Result = Swift.Result<(data: Data, response: HTTPURLResponse), Error>
8    @discardableResult
9    func dispatch(_ request: URLRequest, completion: @escaping (Result) -> Void) -> HTTPClientTask
10}
11
12final class URLSessionHTTPClient: HTTPClient {
13    
14    private let session: URLSession
15    
16    init(session: URLSession) {
17        self.session = session
18    }
19    
20    func dispatch(_ request: URLRequest, completion: @escaping (HTTPClient.Result) -> Void) -> HTTPClientTask {
21        let task = session.dataTask(with: request) { data, response, error in
22            completion(Result {
23                if let error = error {
24                    throw error
25                } else if let data = data, let response = response as? HTTPURLResponse {
26                    return (data, response)
27                } else {
28                    throw UnexpectedValuesRepresentation()
29                }
30            })
31        }
32        task.resume()
33        return URLSessionTaskWrapper(wrapped: task)
34    }
35}
36
37private extension URLSessionHTTPClient {
38    struct UnexpectedValuesRepresentation: Error {}
39    
40    struct URLSessionTaskWrapper: HTTPClientTask {
41        let wrapped: URLSessionTask
42        
43        func cancel() {
44            wrapped.cancel()
45        }
46    }
47}
48extension HTTPClient {
49    typealias Publisher = AnyPublisher<(data: Data, response: HTTPURLResponse), Error>
50
51    func dispatchPublisher(for request: URLRequest) -> Publisher {
52        var task: HTTPClientTask?
53
54        return Deferred {
55            Future { completion in
56                task = self.dispatch(request, completion: completion)
57            }
58        }
59        .handleEvents(receiveCancel: { task?.cancel() })
60        .eraseToAnyPublisher()
61    }
62}
63extension HTTPClient {
64    func dispatch(_ request: URLRequest) async -> HTTPClient.Result {
65
66        let task = Task { () -> (data: Data, response: HTTPURLResponse) in
67            return try await withCheckedThrowingContinuation { continuation in
68                self.dispatch(request) { result in
69                    switch result {
70                    case let .success(values): continuation.resume(returning: values)
71                    case let .failure(error): continuation.resume(throwing: error)
72                    }
73                }
74            }
75        }
76
77        do {
78            let output = try await task.value
79            return .success(output)
80        } catch {
81            return .failure(error)
82        }
83    }
84}
85

However this simply provides the async implementation, I am unable to cancel this.

How should this be handled?

ANSWER

Answered 2021-Oct-10 at 13:42

async/await might not be the proper paradigm if you want cancellation. The reason is that the new structured concurrency support in Swift allows you to write code that looks single-threaded/synchronous, but it fact it's multi-threaded.

Take for example a naive synchronous code:

1
2protocol HTTPClientTask {
3    func cancel()
4}
5
6protocol HTTPClient {
7    typealias Result = Swift.Result<(data: Data, response: HTTPURLResponse), Error>
8    @discardableResult
9    func dispatch(_ request: URLRequest, completion: @escaping (Result) -> Void) -> HTTPClientTask
10}
11
12final class URLSessionHTTPClient: HTTPClient {
13    
14    private let session: URLSession
15    
16    init(session: URLSession) {
17        self.session = session
18    }
19    
20    func dispatch(_ request: URLRequest, completion: @escaping (HTTPClient.Result) -> Void) -> HTTPClientTask {
21        let task = session.dataTask(with: request) { data, response, error in
22            completion(Result {
23                if let error = error {
24                    throw error
25                } else if let data = data, let response = response as? HTTPURLResponse {
26                    return (data, response)
27                } else {
28                    throw UnexpectedValuesRepresentation()
29                }
30            })
31        }
32        task.resume()
33        return URLSessionTaskWrapper(wrapped: task)
34    }
35}
36
37private extension URLSessionHTTPClient {
38    struct UnexpectedValuesRepresentation: Error {}
39    
40    struct URLSessionTaskWrapper: HTTPClientTask {
41        let wrapped: URLSessionTask
42        
43        func cancel() {
44            wrapped.cancel()
45        }
46    }
47}
48extension HTTPClient {
49    typealias Publisher = AnyPublisher<(data: Data, response: HTTPURLResponse), Error>
50
51    func dispatchPublisher(for request: URLRequest) -> Publisher {
52        var task: HTTPClientTask?
53
54        return Deferred {
55            Future { completion in
56                task = self.dispatch(request, completion: completion)
57            }
58        }
59        .handleEvents(receiveCancel: { task?.cancel() })
60        .eraseToAnyPublisher()
61    }
62}
63extension HTTPClient {
64    func dispatch(_ request: URLRequest) async -> HTTPClient.Result {
65
66        let task = Task { () -> (data: Data, response: HTTPURLResponse) in
67            return try await withCheckedThrowingContinuation { continuation in
68                self.dispatch(request) { result in
69                    switch result {
70                    case let .success(values): continuation.resume(returning: values)
71                    case let .failure(error): continuation.resume(throwing: error)
72                    }
73                }
74            }
75        }
76
77        do {
78            let output = try await task.value
79            return .success(output)
80        } catch {
81            return .failure(error)
82        }
83    }
84}
85let data = tryData(contentsOf: fileURL)
86

If the file is huge, then it might take a lot of time for the operation to finish, and during this time the operation cannot be cancelled, and the caller thread is blocked.

Now, assuming Data exports an async version of the above initializer, you'd write the async version of the code similar to this:

1
2protocol HTTPClientTask {
3    func cancel()
4}
5
6protocol HTTPClient {
7    typealias Result = Swift.Result<(data: Data, response: HTTPURLResponse), Error>
8    @discardableResult
9    func dispatch(_ request: URLRequest, completion: @escaping (Result) -> Void) -> HTTPClientTask
10}
11
12final class URLSessionHTTPClient: HTTPClient {
13    
14    private let session: URLSession
15    
16    init(session: URLSession) {
17        self.session = session
18    }
19    
20    func dispatch(_ request: URLRequest, completion: @escaping (HTTPClient.Result) -> Void) -> HTTPClientTask {
21        let task = session.dataTask(with: request) { data, response, error in
22            completion(Result {
23                if let error = error {
24                    throw error
25                } else if let data = data, let response = response as? HTTPURLResponse {
26                    return (data, response)
27                } else {
28                    throw UnexpectedValuesRepresentation()
29                }
30            })
31        }
32        task.resume()
33        return URLSessionTaskWrapper(wrapped: task)
34    }
35}
36
37private extension URLSessionHTTPClient {
38    struct UnexpectedValuesRepresentation: Error {}
39    
40    struct URLSessionTaskWrapper: HTTPClientTask {
41        let wrapped: URLSessionTask
42        
43        func cancel() {
44            wrapped.cancel()
45        }
46    }
47}
48extension HTTPClient {
49    typealias Publisher = AnyPublisher<(data: Data, response: HTTPURLResponse), Error>
50
51    func dispatchPublisher(for request: URLRequest) -> Publisher {
52        var task: HTTPClientTask?
53
54        return Deferred {
55            Future { completion in
56                task = self.dispatch(request, completion: completion)
57            }
58        }
59        .handleEvents(receiveCancel: { task?.cancel() })
60        .eraseToAnyPublisher()
61    }
62}
63extension HTTPClient {
64    func dispatch(_ request: URLRequest) async -> HTTPClient.Result {
65
66        let task = Task { () -> (data: Data, response: HTTPURLResponse) in
67            return try await withCheckedThrowingContinuation { continuation in
68                self.dispatch(request) { result in
69                    switch result {
70                    case let .success(values): continuation.resume(returning: values)
71                    case let .failure(error): continuation.resume(throwing: error)
72                    }
73                }
74            }
75        }
76
77        do {
78            let output = try await task.value
79            return .success(output)
80        } catch {
81            return .failure(error)
82        }
83    }
84}
85let data = tryData(contentsOf: fileURL)
86let data = try await Data(contentsOf: fileURL)
87

For the developer, it's the same coding style, once the operation finishes, they'll either have a data variable to use, or they'll be receiving an error.

In both cases, there's no cancellation built in, as the operation is synchronous from the developer's perspective. The major difference is that the await-ed call doesn't block the caller thread, but on the other hand once the control flow returns it might well be that the code continues executing on a different thread.

Now, if you need support for cancellation, then you'll have to store somewhere some identifiable data that can be used to cancel the operation.

If you'll want to store those identifiers from the caller scope, then you'll need to split your operation in two: initialization, and execution.

Something along the lines of

1
2protocol HTTPClientTask {
3    func cancel()
4}
5
6protocol HTTPClient {
7    typealias Result = Swift.Result<(data: Data, response: HTTPURLResponse), Error>
8    @discardableResult
9    func dispatch(_ request: URLRequest, completion: @escaping (Result) -> Void) -> HTTPClientTask
10}
11
12final class URLSessionHTTPClient: HTTPClient {
13    
14    private let session: URLSession
15    
16    init(session: URLSession) {
17        self.session = session
18    }
19    
20    func dispatch(_ request: URLRequest, completion: @escaping (HTTPClient.Result) -> Void) -> HTTPClientTask {
21        let task = session.dataTask(with: request) { data, response, error in
22            completion(Result {
23                if let error = error {
24                    throw error
25                } else if let data = data, let response = response as? HTTPURLResponse {
26                    return (data, response)
27                } else {
28                    throw UnexpectedValuesRepresentation()
29                }
30            })
31        }
32        task.resume()
33        return URLSessionTaskWrapper(wrapped: task)
34    }
35}
36
37private extension URLSessionHTTPClient {
38    struct UnexpectedValuesRepresentation: Error {}
39    
40    struct URLSessionTaskWrapper: HTTPClientTask {
41        let wrapped: URLSessionTask
42        
43        func cancel() {
44            wrapped.cancel()
45        }
46    }
47}
48extension HTTPClient {
49    typealias Publisher = AnyPublisher<(data: Data, response: HTTPURLResponse), Error>
50
51    func dispatchPublisher(for request: URLRequest) -> Publisher {
52        var task: HTTPClientTask?
53
54        return Deferred {
55            Future { completion in
56                task = self.dispatch(request, completion: completion)
57            }
58        }
59        .handleEvents(receiveCancel: { task?.cancel() })
60        .eraseToAnyPublisher()
61    }
62}
63extension HTTPClient {
64    func dispatch(_ request: URLRequest) async -> HTTPClient.Result {
65
66        let task = Task { () -> (data: Data, response: HTTPURLResponse) in
67            return try await withCheckedThrowingContinuation { continuation in
68                self.dispatch(request) { result in
69                    switch result {
70                    case let .success(values): continuation.resume(returning: values)
71                    case let .failure(error): continuation.resume(throwing: error)
72                    }
73                }
74            }
75        }
76
77        do {
78            let output = try await task.value
79            return .success(output)
80        } catch {
81            return .failure(error)
82        }
83    }
84}
85let data = tryData(contentsOf: fileURL)
86let data = try await Data(contentsOf: fileURL)
87extension HTTPClient {
88    // note that this is not async
89    func task(for request: URLRequest) -> HTTPClientTask {
90        // ...
91    }
92}
93
94class HTTPClientTask {
95    func dispatch() async -> HTTPClient.Result {
96        // ...
97    }
98}
99
100let task = httpClient.task(for: urlRequest)
101self.theTask = task
102let result = await task.dispatch()
103
104// somewhere outside the await scope
105self.theTask.cancel()
106

Source https://stackoverflow.com/questions/69506002

QUESTION

What are the differences between xcodebuild, xcrun and swift command line tools?

Asked 2022-Jan-01 at 19:34

We can build and run Swift code/projects from the command line via multiple commands without using Xcode. I have heard of xcodebuild, xcrun and swift used for Xcode development. I do use fastlane but I don't really understand the tools powering it under the hood.

I am an iOS developer who uses a Mac. I develop using Xcode so I haven't used these command-line tools before.

What are the differences between each command? Are there any cases where I'd be better off using one over the other?

ANSWER

Answered 2021-Sep-13 at 17:36
Tl;DR

xcodebuild and xcrun help build Xcode projects in a headless context, for example in CI setups. swift is the Swift REPL and is largely used for Swift on Server apps. As such, we can build apps without knowing about or using the tools regularly in mobile app development. We use xcodebuild and xcrun under the hood interacting with Xcode even though we don't realise it because they're bundled in Xcode's Command Line tools (documentation archive, but still relevant).

fastlane is an example CI tool that automates the build process, certificate signing, and interfacing with App Store Connect, using these tools.

xcodebuild

xcodebuild is part of Xcode's bundled command-line tools package. From the manpages:

build Xcode projects and workspaces

xcodebuild builds one or more targets contained in an Xcode project, or builds a scheme contained in an Xcode workspace or Xcode project.

xcodebuild has lots of options and use cases. The options are equivalent to certain user actions within the Xcode IDE. Example usage:

1xcodebuild -workspace MyWorkspace.xcworkspace -scheme MyScheme
2

Builds the scheme MyScheme in the Xcode workspace MyWorkspace.xcworkspace.

In the command above, we build the workspace without Xcode, using what Xcode runs internally for compilation. Xcode can only be installed on macOS and we have the same limitations for using its command-line tools, including xcodebuild and xcrun.

xcrun

xcrun is another Xcode command-line tool part of Xcode's CLI tools. From the manpages:

run or locate development tools

xcrun provides a means to locate or invoke coexistence- and platform-aware developer tools from the command-line, without requiring users to modify makefiles or otherwise take inconvenient measures to support multiple Xcode toolchains.

1xcodebuild -workspace MyWorkspace.xcworkspace -scheme MyScheme
2xcrun [-sdk SDK] -find <tool_name>
3

xcrun is also commonly used with Xcode-select to manage multiple Xcode versions on the same machine. Every version of Xcode comes bundled with its own development tools, and we can use xcrun to get the current path to them:

1xcodebuild -workspace MyWorkspace.xcworkspace -scheme MyScheme
2xcrun [-sdk SDK] -find <tool_name>
3xcrun xcode-select --print-path
4
swift

swift is the Swift REPL. swift is a command-line tool that includes the Swift toolchain but can also be installed outside of the Xcode bundled tools. swift is different from xcodebuild and xcrun because it is compiled Swift rather than C. swift is not well documented in the MacOS manpages documentation, however, Apple has documented these tools on its blog:

Xcode 6.1 introduces yet another way to experiment with Swift in the form of an interactive Read Eval Print Loop, or REPL.

A REPL is essentially an interactive compilation environment or shell. First, the REPL reads code, then evaluates it, prints, and repeats the process. As you can imagine, there is much less we can develop using a REPL compared to an IDE. However, there are other use cases for Swift than iOS, watchOS, and macOS development.

swift includes the standard library and doesn't include libraries such as Foundation and UIKit. These Swift libraries are almost certainly needed for iOS or macOS development, so we can't develop apps using the swift REPL alone. However, Swift on Server projects regularly use swift to run Swift code on Linux and even Windows machines.

For wider adoption, Apple has made swift available on different Operating Systems where Xcode is not readily available. Swift now also has Docker support and Windows. Docker enables us to run swift on any machine regardless of the underlying OS. swift in these applications serves as a scripting language.

Bonus notes for SoS

swift is used largely for Swift on Server. Swift on Server has great performance for server applications, with a lower memory footprint, fast startup time, and deterministic performance. Although it is not quite as fast as .NET core for some tasks, this is because Swift is much safer with a rigorous type system, garbage collection with ARC, and fewer optimisations for server-specific apps. Many early adopters praise the improved language type system, memory efficiency, and algorithmic performance. In fact, Swift vapor is comparable to Python and Ruby in efficiency for JSON Serialization tasks. Swift is comparable to Java in very few tasks, but this is likely to change as the language and ecosystem grow.

Source https://stackoverflow.com/questions/69030618

QUESTION

Xcode 13.2 - Adding package hangs on "Preparing to validate"

Asked 2021-Dec-21 at 13:51

I have recently updated to Xcode 13.2 from the Mac App Store. While trying to fix an issue with a Swift package, I uninstalled it and now I cannot reinstall the package.

When I try to add a package from GitHub the process hangs immediately on "Preparing to validate".

I already attempted to restart Xcode, restart my mac, clean derived data, reset Swift package caches and update package versions to no avail.

Is there any way around this issue?Screenshot of issue

ANSWER

Answered 2021-Dec-14 at 04:14

Check https://developer.apple.com/forums/thread/696504 and re-download Xcode 13.2 directly from the releases section of the Apple Developer website: https://developer.apple.com/download/release/

Source https://stackoverflow.com/questions/70342833

QUESTION

Xcode 13.2 - Internal error : Missing Package Description Module

Asked 2021-Dec-20 at 03:33

Just updated Xcode to 13.2 via Mac App Store.

I installed the additional components, and my project won't compile anymore : Xcode just tells me Internal error: missingPackageDescriptionModule - Resolving Package Graph Failed when attempting to build. None of the Swift packages used within my app seems to build, because "Package resolution errors must be fixed before building".

Already attempted to restart Xcode, update macOS, clean derived data, reset Swift package caches and update package versions to no avail.

Guess I'll try re-installing Xcode but... does anyone else have the same issue?

ANSWER

Answered 2021-Dec-20 at 03:33

EDIT: Xcode 13.2.1 version fixes this issue and can be downloaded from the Mac App Store.

Old Answer:

Apple has responded:

We're currently investigating this issue — thank you to those who have filed bug reports so far. To workaround this issue, please re-download Xcode 13.2 RC directly from the More Downloads page.

https://developer.apple.com/forums/thread/696504

Source https://stackoverflow.com/questions/70342174

Community Discussions contain sources that include Stack Exchange Network

Tutorials and Learning Resources in Swift

Tutorials and Learning Resources are not available at this moment for Swift

Share this Page

share link

Get latest updates on Swift