I came across
One Sided Range
Example:
[...2]
[2...]
[..<2]
Half Open Range
[..<2]
Can not the last use case be separated [..<2] of One Sided Range for Brevity as it is already included in Half Open Range?
Dive into the world of programming languages used for app development.
Selecting any option will automatically load the page
Post
Replies
Boosts
Views
Activity
I’m working with Swift and encountered an issue when using the contains method on an array. The following code works fine:
let result = ["hello", "world"].contains(Optional("hello")) // ✅ Works fine
However, when I try to use the same contains method with the array declared in a separate constant(or variable), I get a compile-time error:
let stringArray = ["hello", "world"]
let result = stringArray.contains(Optional("hello")) // ❌ Compile-time error
The compiler produces the following error message:
Cannot convert value of type 'Optional<String>' to expected argument type 'String'
Both examples seem conceptually similar, but the second one causes a compile-time error, while the first one works fine.
This confuses me because I know that Swift automatically promotes a non-optional value to an optional when comparing it with an optional value. This means "hello" should be implicitly converted to Optional("hello") for the comparison.
What I understand so far:
The contains(_:) method is defined as:
func contains(_ element: Element) -> Bool
Internally, it calls contains(where:), as seen in the Swift source code:
🔗 Reference
contains(where:) takes a closure that applies the == operator for comparison.
Since Swift allows comparing String and String? directly (String is implicitly promoted to String? when compared with an optional), I expected contains(where:) to work the same way.
My Questions:
Why does the first example work, but the second one fails with a compile-time error?
What exactly causes this error in the second case, even though both cases involve comparing an optional value with a non-optional value?
Does contains(_:) behave differently when used with an explicit array variable rather than a direct array literal? If so, why?
I know that there are different ways to resolve this, like using nil coalescing or optional binding, but what I’m really looking for is a detailed explanation of why this issue occurs at the compile-time level.
Can anyone explain the underlying reason for this behavior?
Hello guys!
I faced a problem with building...
My device suddenly updated to iOS 15.4.1, my Xcode was 13.2 and I had to update it to the latest version (13.3.1) to build the app. After the update, I had a few problems which were successfully solved but one of them stopped me for a few hours. The problem is with Bridging Headers or Swift Compiler, I really don't know what I did badly, and what causes problems.
On several forums I often read that is important to set:
Build Settings > Build Options > Build Libraries for Distribution
But in any case it doesn't work, on yes:
error: using bridging headers with module interfaces is unsupported
on no:
(line with import framework SWXMLHash) /Users/blablabla/SSLModel.swift:9:8: error: module compiled with Swift 5.5.1 cannot be imported by the Swift 5.6 compiler: /Users/blablabla2/Build/Products/Debug-iphoneos/SWXMLHash.framework/Modules/SWXMLHash.swiftmodule/arm64-apple-ios.swiftmodule
import SWXMLHash
It will be important that I use Carthage.
What should I do?
Clone all 10 frameworks that I use and re-build them with a new Xcode which includes compiler 5.6? That may be a bad solution... Any answers on similar topics don't help..
I've been teaching myself Objective-C and I wanted to start creating projects that don't use ARC to become better at memory management and learn how it all works. I've been attempting to build and run applications, but I'm not really sure where to start as modern iOS development is used with Swift and memory management is handled.
Is there any way to create modern applications that use Objective-C, UIKit, and not use ARC?
I want to know how to format doubles. In the program I have 4.3333 I just want to print 4 to the screen. I just want to print whole numbers. I'm using Swiftui with xcode. Please help. Thank you.
Topic:
Programming Languages
SubTopic:
Swift
I have a VPN application published in the app store. Used Ikev2 for this personal VPN. There are two in-app purchases. One is 'Monthly' and another is 'Yearly' with 3 days free trial. We have seen something strange for the yearly subscriptions which has free trail, the cancellation reason through the billing issue is too high like 70-80% due to billing retry state. Some other apps which have billing issues under 10% always. We have done some research and found that if the user doesn't cancel and Apple is unable to charge then it goes to a billing retry state.
If users don't like the app, they could cancel their subscription/free trail easily but they are not doing this and why Apple unable to charge the bill after the trial ends. Am i missing something in the developer end?
Hello, everyone!
Help me please to find answer. I have two applications: App-1 with share extension and App-2 without it. From the second app I can open share extension via UIActivityViewController. But I need this extension in the second application to open immediately by pressing a button, and not through UIActivityViewController. Can I do this?
I have a workspace with my project and a Swift Macro. When I use the "Build Documentation" command the build fails with this error:
fatal error: module map file '/Users/me/Library/Developer/Xcode/DerivedData/Project-fmdkuqlofexbqdhhitpgjnoqzyrz/Build/Intermediates.noindex/GeneratedModuleMaps-iphoneos/Macros.modulemap' not found
Is there a way around this?
Hi Everyone,
I was able to create the String Catalog with all my strings getting automatic into the stringCatalog except the strings from my models where is not swiftUI and where all I have a class with a lot of info for my app.
Some classes are short and I was able to just make the strings localizable by adding on every line:
(String(localized: "Telefone"))
But I have one class which has Line: 1071 and Col: 1610 and every line I have 7 strings that needs to get localized. These 7 strings are repeated on every line.
So I was trying to create a localization for these 7 strings on this class without having to write (String(localized: "Telefone")) 7 times on every line.
is there a way?
Here is short version of my class:
import Foundation
class LensStructFilter: Identifiable {
var description: String
init(description: String) {
self.description = description
}
}
let lensEntriesFilter: [LensStructFilter] = [
LensStructFilter(description: "Focal: 24mm \nAbertura Máxima: F2.8 \nCobertura: FULL FRAME \nBocal: Nikon F \nFoco Mínimo: 0,30m \nDiâmetro Frontal: 52mm \nPeso: 275g \n\nFocal: 35mm \nAbertura Máxima: F2.0 \nCobertura: FULL FRAME \nBocal: Nikon F \nFoco Mínimo: 0,25m \nDiâmetro Frontal: 52mm \nPeso: 205g \n\nFocal: 50mm \nAbertura Máxima: F1.8 \nCobertura: FULL FRAME \nBocal: Nikon F \nFoco Mínimo: 0,45m \nDiâmetro Frontal: 52mm \nPeso: 185g \n\nFocal: 85mm \nAbertura Máxima: F1.8 \nCobertura: FULL FRAME \nBocal: Nikon F \nFoco Mínimo: 0,80m \nDiâmetro Frontal: 67mm \nPeso: 350g \n\nFocal: 105mm MACRO \nAbertura Máxima: F2.8 \nCobertura: FULL FRAME \nBocal: Nikon F \nFoco Mínimo: 0,31m \nDiâmetro Frontal: 62mm \nPeso: 720g"),
LensStructFilter(description: "Focal: 16-35mm \nAbertura Máxima: F2.8 \nCobertura: FULL FRAME \nBocal: EF \nFoco Mínimo: 0,28m \nDiâmetro Frontal (rosca): 82mm \nPeso: 790Kg"),
Thanks
This is not a question but more of a hint where I was having trouble with. In my SwiftData App I wanted to move from Swift 5 to Swift 6, for that, as recommended, I stayed in Swift 5 language mode and set 'Strict Concurrency Checking' to 'Complete' within my build settings.
It marked all the places where I was using predicates with the following warning:
Type '' does not conform to the 'Sendable' protocol; this is an error in the Swift 6 language mode
I had the same warnings for SortDescriptors.
I spend quite some time searching the web and wrapping my head around how to solve that issue to be able to move to Swift 6. In the end I found this existing issue in the repository of the Swift Language https://github.com/swiftlang/swift/issues/68943. It says that this is not a warning that should be seen by the developer and in fact when turning Swift 6 language mode on those issues are not marked as errors.
So if anyone is encountering this when trying to fix all issues while staying in Swift 5 language mode, ignore those, fix the other issues and turn on Swift 6 language mode and hopefully they are gone.
I generate images with command line apps in Swift on MacOS. Under the prior Xcode/MacOS my code had been running at the same performance for years. Converting to Swift 6 (no code changes) and running on Sequoia, I noticed a massive slowdown. Running Profile, I tracked it down to allow single line:
var values = ContiguousArray<Double>(repeating: 0.0, count: localData.options.count)
count for my current test case is 4, so its allocating 4 doubles at a time, around 40,000 times in this test. This one line takes 42 seconds out of a run time of 52 seconds. With the profile shown as:
26 41.62 s 4.8% 26.00 ms specialized ContiguousArray.init(_uninitializedCount:)
42 41.57 s 4.8% 42.00 ms _ContiguousArrayBuffer.init(_uninitializedCount:minimumCapacity:)
40730 40.93 s 4.7% 40.73 s _swift_allocObject_
68 68.00 ms 0.0% 68.00 ms std::__1::pair<MallocTypeCacheEntry*, unsigned int> swift::ConcurrentReadableHashMap<MallocTypeCacheEntry, swift::LazyMutex>::find<unsigned int>(unsigned int const&, swift::ConcurrentReadableHashMap<MallocTypeCacheEntry, swift::LazyMutex>::IndexStorage, unsigned long, MallocTypeCacheEntry*)
7 130.00 ms 0.0% 7.00 ms swift::swift_slowAllocTyped(unsigned long, unsigned long, unsigned long long)
which is clearly inside the OS allocator somewhere. What happened? Previously this would have taken closer to 8 seconds or so for the entire run.
I have an @objC used for notification.
kTag is an Int constant, fieldBeingEdited is an Int variable.
The following code fails at compilation with error: Command CompileSwift failed with a nonzero exit code if I capture self (I edited code, to have minimal case)
@objc func keyboardDone(_ sender : UIButton) {
DispatchQueue.main.async { [self] () -> Void in
switch fieldBeingEdited {
case kTag : break
default : break
}
}
}
If I explicitly use self, it compiles, even with self captured:
@objc func keyboardDone(_ sender : UIButton) {
DispatchQueue.main.async { [self] () -> Void in
switch fieldBeingEdited { // <<-- no need for self here
case self.kTag : break // <<-- self here
default : break
}
}
}
This compiles as well:
@objc func keyboardDone(_ sender : UIButton) {
DispatchQueue.main.async { () -> Void in
switch self.fieldBeingEdited { // <<-- no need for self here
case self.kTag : break // <<-- self here
default : break
}
}
}
Is it a compiler bug or am I missing something ?
Hello, I have a problem with the .onMove function. I believe I have set everything up properly. However, the moving does not seem to be working correctly. When I try to move the item, it is highlighted first, as it is supposed to be. Then, while I am moving it through the list, it disappears for some reason, and at the end of the move, it comes back to its initial place. (I use iOS 16.0 minimum, so I don't have to include the EditButton(). It works the same in the edit mode tho)
import SwiftUI
struct Animal: Identifiable {
var id = UUID()
var name: String
}
struct ListMove: View {
@State var animals = [Animal(name: "Dog"), Animal(name: "Cat"), Animal(name: "Cow"), Animal(name: "Goat"), Animal(name: "Chicken")]
var body: some View {
List {
ForEach(animals) { animal in
Text(animal.name)
}
.onMove(perform: move)
}
}
func move(from source: IndexSet, to destination: Int) {
animals.move(fromOffsets: source, toOffset: destination)
}
}
#Preview {
ListMove()
}
Greetings,
func stepForward(_ input: Int) -> Int {
return input + 1
}
func stepBackward(_ input: Int) -> Int {
return input - 1
}
func chooseStepFunction(backward: Bool) -> (Int) -> Int {
return backward ? stepBackward : stepForward /* Error
type of expression is ambiguous without a type annotation */
}
Why am I getting this error. If I change the function to
func chooseStepFunction(backward: Bool) -> (Int) -> Int {
if backward {
return stepBackward
else {
return stepForward
}
}
Why is the previous chooseStepFunction giving me an error ?
Thx in advance
Hello,
It is mentioned in CryptoTokenKit documentation:
You use the CryptoTokenKit framework to easily access cryptographic tokens. Tokens are physical devices built in to the system, located on attached hardware (like a smart card), or accessible through a network connection.
However, it looks like there is lack of documentation with simple example, how to access network token.
I have a certificates in HSM (hardware secure module), which is accessible on network, and I'd like to access certificates on HSM on my Mac.
Does anybody know, where to start with implementation?
Thank you.
Just read about the new @concurrent option coming to Swift 6.2 and lover it, but...
It just me, but I which these options would pick a case and stick with it...
@Sendable
@unchecked
@MainActor
@concurrent
@Observable
@ObservationIgnored
When swizzling NSURLRequest initialiser and returning a mutable copy, the original instance does not get deallocated and eventually gets leaked and a crash follows after that.
Here's the swizzling setup:
static func swizzleInit() {
let initSel = NSSelectorFromString("initWithURL:cachePolicy:timeoutInterval:")
guard let initMethod = class_getInstanceMethod(NSClassFromString("NSURLRequest"), initSel) else {
return
}
let origInitImp = method_getImplementation(initMethod)
let block: @convention(block) (AnyObject, Any, NSURLRequest.CachePolicy, TimeInterval) -> NSURLRequest = { _self, url, policy, interval in
typealias OrigInit = @convention(c) (AnyObject, Selector, Any, NSURLRequest.CachePolicy, TimeInterval) -> NSURLRequest
let origFunc = unsafeBitCast(origInitImp, to: OrigInit.self)
let request = origFunc(_self, initSel, url, policy, interval)
return request.tagged()
}
let newImplementation = imp_implementationWithBlock(block as Any)
method_setImplementation(initMethod, newImplementation)
}
// create a mutable copy if needed and add a header
private func tagged() -> NSURLRequest {
guard let mutableRequest = self as? NSMutableURLRequest ?? self.mutableCopy() as? NSMutableURLRequest else {
return self
}
mutableRequest.setValue("test", forHTTPHeaderField: "test")
return mutableRequest
}
Then, we have a few test cases:
// memory leak and crash
func testSwizzleNSURLRequestInit() {
let request = NSURLRequest(url: URL(string: "https://example.com")!)
XCTAssertEqual(request.value(forHTTPHeaderField: "test"), "test")
}
// no crash, as the request is mutable, so no copy is created
func testSwizzleNSURLRequestInit2() {
let request = URLRequest(url: URL(string: "https://example.com")!)
XCTAssertEqual(request.value(forHTTPHeaderField: "test"), "test")
}
// no crash, as the request is mutable, so no copy is created
func testSwizzleNSURLRequestInit3() {
let request = NSMutableURLRequest(url: URL(string: "https://example.com")!)
XCTAssertEqual(request.value(forHTTPHeaderField: "test"), "test")
}
// no crash, as the new instance does not get deallocated
// when the test method completes (?)
var request: NSURLRequest?
func testSwizzleNSURLRequestInit4() {
request = NSURLRequest(url: URL(string: "https://example.com")!)
XCTAssertEqual(request?.value(forHTTPHeaderField: "test"), "test")
}
It appears a memory leak occurs only when any other instance except for the original one is being returned from the initialiser.
Is there a workaround to prevent the leak, while allowing for modifications of all requests?
Hi all,
I am trying to use this guide to link directly to symbols in my documentation. But I am unable to get it to link to an Objective-C enum case. For example
``EnumNameType/EnumNameMyCase``
does not create a link. It works fine for method names, etc. I have tried all of the combinations I can think of, but I can't get it to work.
Any help is much appreciated!
So any time I create a class that's both @Observable and Codable, e.g.
@Observable class GameLocationManager : Codable {
I get a warning in the macro expansion code:
@ObservationIgnored private let _$observationRegistrar = Observation.ObservationRegistrar()
Immutable property will not be decoded because it is declared with an initial value which cannot be overwritten.
I've been ignoring them for now, but there are at least a half a dozen of them now in my (relatively small) codebase, and I'd like to find a solution (ideally one that doesn't require me to write init(decoder:) for every @Observable class in my project...), especially since I'm not sure what the actual consequences of ignoring this might be.
I am currently studying the Accelerate library by referring to Apple documentation.
Here is the link to the referenced document:
https://developer.apple.com/documentation/accelerate/veclib/vforce
When I executed the sample code provided at the bottom of the document, I found a case where the results were different.
let n = 10_000
let x = (0..<n).map { _ in
Float.random(in: 1 ... 10_000)
}
let y = x.map {
return sqrt($0)
}
and
let y = [Float](unsafeUninitializedCapacity: n) { buffer, initializedCount in
vForce.sqrt(x,
result: &buffer)
initializedCount = n
}
The code below is provided to observe the issue described above.
import Accelerate
Task {
let n = 1//10_000
let x = (0..<n).map { _ in
Float(6737.015)//Float.random(in: 1 ... 10_000)
}
let y = x.map {
return sqrt($0)
}
try? await Task.sleep(nanoseconds: 1_000_000_000)
let z = [Float](unsafeUninitializedCapacity: n) { buffer, initializedCount in
vForce.sqrt(x, result: &buffer)
initializedCount = n
}
}
For a value of 6737.015 when calculating the square root:
Using the sqrt(_:) function gives the result 82.07932,
While using the vForce.sqrt(_:result:) function gives the result 82.07933.
Using a calculator, the value comes out as 82.07932139, which shows that the result from vForce is incorrect.
Could you explain the reason behind this difference?