[swift-users] Question about "lazy initialization" in CommandLine.arguments documentation

2018-01-11 Thread Martin R via swift-users
The `CommandLine` documentation 
(https://developer.apple.com/documentation/swift/commandline) states about the 
`arguments` property:

... also use lazy initialization of static properties to safely initialize 
the swift arguments.

Apparently this originates from the markup comments in 
https://github.com/apple/swift/blob/master/stdlib/public/core/CommandLine.swift#L48:

/// Access to the swift arguments, also use lazy initialization of static
/// properties to safely initialize the swift arguments.
public static var arguments: [String]
  = (0..

Re: [swift-users] Cast CFString to String

2017-12-05 Thread Martin R via swift-users
Another workaround would be

public init(uti: String) {
switch uti.lowercased() {
case String(kUTTypeText):
self = .text
default:
self = .unknown
}
}

because there is a `String(_ cocoaString: NSString)` initializer in Foundation.

Regards, Martin


> Am 05.12.2017 um 10:09 schrieb Dennis Weissmann via swift-users 
> :
> 
> Hi swift-users,
> 
> I have found another weird behavior (IMO) and wanted to ask for the right way 
> to handle this:
> 
> Imagine I want to switch over a Swift string which contains a UTI to map that 
> UTI to an enum.
> 
> (A playground is attached for you to easily reproduce, this is tested with 
> Xcode 9.1's included toolchain, also happens in projects)
> 
> I would expect the following to work:
> 
> import MobileCoreServices
> 
> enum MimeType {
> 
> case text
> case unknown
> 
> public init(uti: String) {
> // Source: 
> https://developer.apple.com/library/content/documentation/Miscellaneous/Reference/UTIRef/Articles/System-DeclaredUniformTypeIdentifiers.html
> switch uti.lowercased() {
> case kUTTypeText as String:
> self = .text
> default:
> self = .unknown
> }
> }
> 
> }
> 
> The error I get here is
> 
> warning: UTITest.playground:8:26: warning: 'as' test is always true
> case kUTTypeText as String:
>  ^
> 
> error: UTITest.playground:8:14: error: expression pattern of type 'CFString' 
> cannot match values of type 'String'
> case kUTTypeText as String:
>  ^~~
>  ^~~
> The only way I found to resolve this is to also import Foundation (which 
> makes sense but is not really obvious).
> 
> Alright, that gives me this:
> 
> import MobileCoreServices
> import Foundation
> 
> enum MimeType {
> 
> case text
> case unknown
> 
> public init(uti: String) {
> // Source: 
> https://developer.apple.com/library/content/documentation/Miscellaneous/Reference/UTIRef/Articles/System-DeclaredUniformTypeIdentifiers.html
> switch uti.lowercased() {
> case kUTTypeText as String:
> self = .text
> default:
> self = .unknown
> }
> }
> 
> }
> 
> warning: UTITest.playground:8:26: warning: 'as' test is always true
> case kUTTypeText as String:
>  ^
> 
> error: UTITest.playground:8:14: error: 'CFString' is not implicitly 
> convertible to 'String'; did you mean to use 'as' to explicitly convert?
> case kUTTypeText as String:
>  ^
>  as String
> 
> 
> Uhm, okay? So let's do that:
> 
> enum MimeType {
> 
> case text
> case unknown
> 
> public init(uti: String) {
> // Source: 
> https://developer.apple.com/library/content/documentation/Miscellaneous/Reference/UTIRef/Articles/System-DeclaredUniformTypeIdentifiers.html
> switch uti.lowercased() {
> case kUTTypeText as String as String:
> self = .text
> default:
> self = .unknown
> }
> }
> 
> }
> 
> As weird as it looks, it works ... My question is: Is this behavior intended?
> 
> Thanks!
> 
> - Dennis
> 
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] Modulo operation in Swift?

2017-11-09 Thread Martin R via swift-users
There was a discussion in swift-evolution, starting at

  
https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20160516/018521.html

about adding a "true modulo" operator to the standard library. There were 
different opinions whether

- such a thing needs to be in the standard library at all, and if yes:
- if it should be an operator or function,
- how it should be named.

As far as I know, nothing happened until now. The above posting contains a 
possible (Swift 3) implementation. In Swift 4 that would be

infix operator %%: MultiplicationPrecedence

func %%(lhs: T, rhs: T) -> T {
return (lhs % rhs + rhs) % rhs
}

I would probably do (as an operator or as a function)

func %%(lhs: T, rhs: T) -> T {
let rem = lhs % rhs // -rhs <= rem <= rhs
return rem >= 0 ? rem : rem + rhs
}

with one division instead of two.

Regards, Martin

> Am 09.11.2017 um 12:43 schrieb Jens Persson via swift-users 
> :
> 
> Hi all!
> Is there a modulo operation/function in Swift? I want the "true" mathematical 
> modulo (as % in Python), and not remainder (as % in Swift).
> 
> Do I have to implement this basic mathematical function myself and if so what 
> is the best way to write it (it will be heavily used so I want it to be as 
> fast as possible)?
> 
> /Jens
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] Was the String contains(_:) method changed in Swift 4?

2017-11-08 Thread Martin R via swift-users
Unicode correct string comparison _is_ tricky, but `s.contains(s)` will always 
be true :)

And `s.contains(ss)` with your example strings return false.

Regards, Martin

> Am 08.11.2017 um 09:56 schrieb Quinn The Eskimo! via swift-users 
> <swift-users@swift.org>:
> 
> 
> On 8 Nov 2017, at 08:47, Martin R via swift-users <swift-users@swift.org> 
> wrote:
> 
>> but apparently only if Foundation is imported.
> 
> Which isn’t a huge surprise when you consider how tricky string containment 
> is.
> 
> import Foundation
> 
> // U+00DF LATIN SMALL LETTER SHARP S
> 
> let s = "Friedrichstra\u{df}e"
> let ss = "strasse"
> if s.contains(s) {
>print("It's a street!")
> }
> 
> Share and Enjoy
> --
> Quinn "The Eskimo!"<http://www.apple.com/developer/>
> Apple Developer Relations, Developer Technical Support, Core OS/Hardware
> 
> 
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] Swift 4 Strings and flatMap

2017-10-21 Thread Martin R via swift-users
Compare  https://bugs.swift.org/browse/SR-1570 : Swift can infer the return 
type from single-statement closures, but not from multi-statement closures. 
Therefore in 

let result = strArr.flatMap { x in
return x
}

the closure type is inferred as (String)-> String, and therefore the flatMap 
call matches exactly the 

   func flatMap(_ transform: (Self.Element) throws -> 
SegmentOfResult) rethrows -> [SegmentOfResult.Element]
   where SegmentOfResult : Sequence

Sequence method, with Self.Element == String and SegmentOfResult == String, and 
flatMap returns [SegmentOfResult.Element] == [Character].

In

let result = strArr.flatMap { x in
print(x)
return x
}

the closure return type is not inferred from the closure itself, because it is 
a multi-statement closure. Here the compiler (apparently) chooses the

public func flatMap(_ transform: (Element) throws -> String?) rethrows -> 
[String]

Array method, and promotes `String` to `String?`. You would get the same result 
with an explicit return type in the single-statement closure:

let result = strArr.flatMap { x -> String? in
return x
}

But why do you use flatMap at all? If the intention is to map [String] to 
[String] then map() would be the right method:

let strArr = ["Hi", "hello"]
let result: [String] = strArr.map { x in
return x
}
print(result) // ["Hi", "hello"]

Regards, Martin


> On 21. Oct 2017, at 02:50, Santiago Gil via swift-users 
>  wrote:
> 
> Hi Swift users,
> 
> I just ran into a bug after a Swift 4 migration where we expected [String] 
> and got [Character] from a flatMap since flatMap will flatten the String 
> since it's now a collection.  While I understand why flatMap behaves this way 
> now that string are collections, in testing this I found some weird 
> behaviour...
> 
> var strArr = ["Hi", "hello"]
> 
> let result = strArr.flatMap { x in
> 
> return x
> 
> }
> 
> 
> The type of results ends up being [Character] in the above case. However, 
> adding a print statement changes things.
> 
> 
> var strArr = ["Hi", "hello"]
> 
> let result = strArr.flatMap { x in
> 
> print(x)
> 
> return x
> 
> }
> 
> In this case, result is of type [String]
> 
> This seems like a bug, or is this expected Swift behaviour?
> 
> Thanks,
> 
> Santiago
> 
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] Why does the withUnsafeMutableBufferPointer closure take an inout parameter?

2017-10-14 Thread Martin R via swift-users

> On 14. Oct 2017, at 13:15, Geordie Jay via swift-users 
>  wrote:
> 
> Chris Lattner  schrieb am Sa. 14. Okt. 2017 um 05:18:
> 
>> On Oct 13, 2017, at 7:40 PM, Andrew Trick via swift-users 
>>  wrote:
>> 
>> 
>> 
>>> On Oct 12, 2017, at 3:52 AM, Geordie Jay via swift-users 
>>>  wrote:
>>> 
>>> 
>>> Guillaume Lessard via swift-users  schrieb am Mi. 
>>> 11. Okt. 2017 um 23:49:
>>> A lot of the MutableCollection implementation is in protocol extensions 
>>> (swapAt, for example.)
>>> 
>>> Should an additional version be written just for the Unsafe*BufferPointer 
>>> types?
>>> 
>>> Makes sense to me, given the examples above. It doesn’t seem to be a high 
>>> priority task though, and one one suited to a contributor pull request 
>>> rather than taking resources away from the core team.
>>> 
>>> Would this kind of change need to go through swift evolution or is it a “no 
>>> brainer”?
>>> 
>>> Geordie
>> 
>> I’ll just point out that it’s already the case that methods defined in 
>> Unsafe*BufferPointer that write to memory are “nonmutating”. So I think it’s 
>> both a “no brainer” and needs to go through evolution.
> 
> I’m not familiar with the specifics of this “proposal” but if it really is 
> just moving something obvious from being a mutating member to a nonmutating 
> member, then I’m sure the core team can find a fast-path way to accept it 
> without a formal review period.
> 
> I’m not 100% sure either tbh, although I can imagine putting in a PR for it 
> once i understand it.
> 
> The issue with changing .swapTo (et al.?) to nonmutating is that semantically 
> it really is a mutation. But pointers as collections have different mutation 
> semantics to other collections: Mutating an Array’s storage is the same as 
> mutating its value, whereas a pointer’s value is its address, not its storage.
> 
> Making the Unsafe*Pointer MutableCollection methods themselves nonmutating 
> probably wouldn’t be a source-breaking change (it’d just lower the “bar of 
> entry” to include let constant instances too). I imagine this is 
> noncontroversial.
> 
> The original question though was about why .withUnsafeMutableBufferPointer 
> takes a closure whose first argument is an *inout* 
> UnsafeMutableBufferPointer, implying that its base address could legally be 
> mutated. This was probably done to ease use of MutableCollection methods 
> given the var parameter. That would no longer be necessary given the first 
> change.
> 
> But removing the inout attribute would be source-breaking. And maybe people 
> really are moving around the array storage’s base address? This seems like a 
> very bad idea to me but it’s currently part of that API contract. In any case 
> this change would need to go through evolution, right?

At present, the withUnsafeMutableBufferPointer() method verifies that the base 
address has not been modified upon return from the closure: 


https://github.com/apple/swift/blob/master/stdlib/public/core/Arrays.swift.gyb#L1750

// Put the working array back before returning.
defer {
  _precondition(
inoutBufferPointer.baseAddress == pointer &&
inoutBufferPointer.count == count,
"${Self} withUnsafeMutableBufferPointer: replacing the buffer is not 
allowed")

  (work, self) = (self, work)
}

That check would become obsolete if the buffer pointer is a constant.

As far as I can see, MutableCollection defines four mutating methods: swapAt(), 
sort(), reverse(), and partition(). Implementing those as non-mutating methods 
of UnsafeMutableBufferPointer seems natural to me.

In addition, it would allow to make the closure parameter in 
withUnsafeMutableBufferPointer() a constant. Mutating that pointer in the 
closure is not allowed anyway. 

Btw, I came up with these questions because I noticed that this compiles:

func foo(bufptr: UnsafeMutableBufferPointer) { }
var a = [1, 2, 3, 4, 5]
a.withUnsafeMutableBufferPointer { foo(bufptr: $0) }

but this does not compile:

a.withUnsafeMutableBufferPointer(foo)
// error: cannot convert value of type '(UnsafeMutableBufferPointer) 
-> ()'
// to expected argument type '(inout UnsafeMutableBufferPointer) -> _'

which looks strange at first sight. With a constant closure parameter, the 
second version would compile as well.

Any advice how to proceed with this "issue" would be appreciated: File a bug 
report? Post on swift-evolution? Make a proposal? ... However, I am not 
familiar with those evolution procedures. I won't mind to sidestep if someone 
else want to jump in. 

Martin

> 
> - Geordie
> 
> 
> -Chris
> 
> 
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

___
swift-users mailing list
swift-users@swift.org

Re: [swift-users] Why does the withUnsafeMutableBufferPointer closure take an inout parameter?

2017-10-10 Thread Martin R via swift-users
Thank you Howard for you response! However, I have a follow-up question:

Why are UnsafeMutableBufferPointer methods which modify not the buffer pointer 
itself, but only the pointed-to memory, mutating at all?

UnsafeMutable(Buffer)Pointer already have non-mutating subscript setters, which 
means that I can modify the pointed-to memory even if the buffer pointer itself 
is a constant. For example, this compiles and runs without problems:

func foo(bufptr: UnsafeMutableBufferPointer) {
let tmp = bufptr[0]
bufptr[0] = bufptr[1]
bufptr[1] = tmp
}

var a = [1, 2, 3, 4, 5]
a.withUnsafeMutableBufferPointer { foo(bufptr: $0) }


Doing the same with swapAt() does not compile:

func bar(bufptr: UnsafeMutableBufferPointer) {
bufptr.swapAt(0, 1)
// error: cannot use mutating member on immutable value: 'bufptr' is a 
'let' constant
}

which means that I have to use a variable copy:

func bar(bufptr: UnsafeMutableBufferPointer) {
var bufptr = bufptr
bufptr.swapAt(0, 1)
}

So my "feeling" is that methods (like swapAt) which modify the pointed-to 
memory of an UnsafeMutableBufferPointer should be non-mutating. 

That would then also allow (coming back to my original question) that 
withUnsafeMutableBufferPointer() passes a _constant_ buffer pointer to the 
closure, and _might_ make the check at

   
https://github.com/apple/swift/blob/master/stdlib/public/core/Arrays.swift.gyb#L1750
   
obsolete (which verifies that the closure did not modify the pointer or length).

I am probably overlooking something, so please let me know where I am wrong!

Regards, Martin

> On 9. Oct 2017, at 01:15, Howard Lovatt <howard.lov...@gmail.com> wrote:
> 
> If it isn't an `inout` then it is a `let` not a `var` and hence you can't 
> call mutating methods on it. There is no 'invar' in Swift, best you can do is 
> `inout`.
> 
>   -- Howard.
> 
> On 9 October 2017 at 06:14, Martin R via swift-users <swift-users@swift.org> 
> wrote:
> I wonder why the closure in the Array method
> 
> mutating func withUnsafeMutableBufferPointer(_ body: (inout 
> UnsafeMutableBufferPointer) throws -> R) rethrows -> R
> 
> takes an _inout_ parameter. The closure is called with a pointer to the 
> contiguous array storage, and I fail to imagine an example where it makes 
> sense to assign a new value to the parameter.
> 
> Any insights are welcome!
> 
> Regards, Martin
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users
> 

___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


[swift-users] Why does the withUnsafeMutableBufferPointer closure take an inout parameter?

2017-10-08 Thread Martin R via swift-users
I wonder why the closure in the Array method

mutating func withUnsafeMutableBufferPointer(_ body: (inout 
UnsafeMutableBufferPointer) throws -> R) rethrows -> R

takes an _inout_ parameter. The closure is called with a pointer to the 
contiguous array storage, and I fail to imagine an example where it makes sense 
to assign a new value to the parameter.

Any insights are welcome!

Regards, Martin
___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] How do you declare a custom NSAttributedStringKey in Objective-C for Swift use?

2017-09-27 Thread Martin R via swift-users
Could it be that this is (just) a problem of the generated interface _view_ ? 
With

extern NSAttributedStringKey ODRolloverTokenAttributeName;

in an Objective-C header the "Generated Interface" is displayed as

   public static let ODRolloverTokenAttributeName: NSAttributedStringKey

as you noticed, but I can use it from Swift as

   let key = NSAttributedStringKey.ODRolloverTokenAttributeName

so it is actually a property of NSAttributedStringKey, not a global variable. 
And with

   extern NSAttributedStringKey ODRolloverTokenAttributeName 
NS_SWIFT_NAME(rolloverToken);

in the Objective-C header I can use it from Swift as

   let key = NSAttributedStringKey.rolloverToken

So – unless I am misunderstanding something – the ODRolloverTokenAttributeName 
defined in the Objective-C header file is actually imported to Swift as an 
extension to NSAttributedStringKey, even if the generated interface view in 
Xcode displays it as a global variable.

Regards, Martin


> Am 27.09.2017 um 16:07 schrieb Marco Masser via swift-users 
> :
> 
> Hi,
> 
> Swift 4 and the macOS 10.13 SDK added a new NSAttributedStringKey type for 
> the keys that NSAttributedStrings use. The keys are then defined in an 
> extension of NSAttributedStringKey, essentially like this in AppKit:
> 
> // AppKit/NSAttributedString.h (Objective-C)
> extern NSAttributedStringKey NSFontAttributeName;
> 
> // Generated Swift Interface
> extension NSAttributedStringKey {
> public static let font: NSAttributedStringKey
> }
> 
> 
> How do I get my own custom NSAttributedStringKeys to be imported this way? 
> When I do it like AppKit, it doesn’t seem to work:
> 
> // My Objective-C header
> extern NSAttributedStringKey ODRolloverTokenAttributeName;
> 
> // Generated Swift Interface
> static let ODRolloverTokenAttributeName: NSAttributedStringKey
> 
> 
> That is obviously not the same. I tried using the NS_SWIFT_NAME macro, but 
> that results in the symbol disappearing in Swift completely:
> 
> // My Objective-C header
> extern NSAttributedStringKey ODRolloverTokenAttributeName 
> NS_SWIFT_NAME(NSAttributedStringKey.rolloverToken);
> 
> 
> I also tried to use the swift_name attribute that is used by the 
> NS_SWIFT_NAME macro and that is even mentioned in SE-0044 for exactly this 
> purpose, but the symbol still disappears:
> https://github.com/apple/swift-evolution/blob/master/proposals/0044-import-as-member.md#swift_name-attribute
> 
> extern const NSAttributedStringKey ODRolloverTokenAttributeName 
> __attribute__((swift_name("NSAttributedStringKey.rolloverToken")));
> 
> 
> What works is to manually define it in an extension like this, but that’s no 
> fun:
> 
> // My Objective-C header
> extern NSAttributedStringKey ODRolloverTokenAttributeName 
> NS_REFINED_FOR_SWIFT;
> 
> extension NSAttributedStringKey {
> static let rolloverToken = 
> NSAttributedStringKey(__ODRolloverTokenAttributeName.rawValue)
> }
> 
> 
> Is there no way to import this automatically? Was this functionality removed 
> before release even though it was mentioned in SE-0044?
> 
> Cheers,
> 
> Marco
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] range(of:options:range:locale:) with partial ranges

2017-09-26 Thread Martin R via swift-users

> On 22. Sep 2017, at 23:55, Ben Cohen <ben_co...@apple.com> wrote:
> 
> In order to be able to use pos… this function would need to be converted from 
> it’s current signature (that takes a concrete Range) to be generic over any 
> RangeExpression.In this case of this method, the range is optional – and in 
> case of nil (which is the default) there would be insufficient context to 
> determine the actual type of the RangeExpression. So we’d need to have an 
> overload instead.
> 
> But none of this ought to be necessary, because constant time slicing and 
> index sharing means we don’t need to have functions take optional range 
> arguments any more. Instead you can just write str[pos...].range(of: “f”). 

That makes sense.

> 
> Except... this technique has a bug in it for this particular method when used 
> on substrings, that we need to fix before that can be used instead. Hoping 
> for that to be fixed on master soon...

Good to know!

Regards, Martin

> 
>> On Sep 21, 2017, at 2:44 AM, Martin R via swift-users <swift-users@swift.org 
>> <mailto:swift-users@swift.org>> wrote:
>> 
>> The range(of:options:range:locale:) method of StringProtocol does not accept 
>> a partial range as search range. Example (Xcode 9, Swift 4):
>> 
>> let str = "foo"
>> let pos = str.startIndex
>> let r = str.range(of: "f", range: pos...)
>> // error: cannot convert value of type 'PartialRangeFrom'
>> // to expected argument type 'Range?'
>> 
>> Is that because it is an NSString method imported to Swift? Would it make 
>> sense to file an enhancement request?
>> 
>> Regards, Martin
>> 
>> ___
>> swift-users mailing list
>> swift-users@swift.org <mailto:swift-users@swift.org>
>> https://lists.swift.org/mailman/listinfo/swift-users
> 

___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] Where to report this bug?

2017-09-22 Thread Martin R via swift-users
Filed as https://bugs.swift.org/browse/SR-5964 


Martin

> On 22. Sep 2017, at 12:11, Alex Blewitt  wrote:
> 
> Hmm... probably worth filing a bug at https://bugs.swift.org 
>  then with the below test case.
> 
> Alex
> 
>> On 22 Sep 2017, at 10:14, Martin R > > wrote:
>> 
>> But the purpose of 
>> 
>> func dividedReportingOverflow(by other: Int 
>> ) -> (partialValue: Int 
>> , overflow: Bool 
>> )
>> 
>> is to report an overflow in the return value. And actually this compiles and 
>> runs in Xcode 9 if the code is on top-level in main.m:
>> 
>> let minusOne = -1
>> let r1 = Int.min.dividedReportingOverflow(by: minusOne)
>> print(r1) // (partialValue: -9223372036854775808, overflow: true)
>> 
>> let zero = 0
>> let r2 = Int.min.dividedReportingOverflow(by: zero)
>> print(r2) // (partialValue: -9223372036854775808, overflow: true)
>> 
>> But the same code inside a function (or do-block) fails to compile:
>> 
>> func foo() {
>> let minusOne = -1
>> let r1 = Int.min.dividedReportingOverflow(by: minusOne)
>> // error: division '-9223372036854775808 / -1' results in an overflow
>> print(r1)
>> 
>> let zero = 0
>> let r2 = Int.min.dividedReportingOverflow(by: zero)
>> // error: division by zero
>> print(r2)
>>}
>> 
>> Martin
>> 
>> 
>>> On 22. Sep 2017, at 10:19, Alex Blewitt via swift-users 
>>> > wrote:
>>> 
>>> Int.min is the smallest negative value, and Int.max is the largest positive 
>>> value (that fits in an Int). However, the absolute value of Int.min is 
>>> larger than the absolute value of Int.max. So you can't convert Int.min 
>>> into -Int.min because it's larger than Int.max.
>>> 
>>> In other words, this is expected behaviour :)
>>> 
>>> For example:
>>> 
>>> Int.min + Int.max = 1
>>> 
>>> If they were the same value, it would be zero.
>>> 
>>> Alex
>>> 
 On 22 Sep 2017, at 02:42, Peter W A Wood via swift-users 
 > wrote:
 
 Entering the following statement in a playground gives an overflow error. 
 Where should I report this?
 
 Statement:
 
 Int.min.dividedReportingOverflow(by:-1)
 
 Playground log:
 
 Playground execution failed:
 
 error: MyPlayground.playground:3:9: error: division '-9223372036854775808 
 / -1' results in an overflow
 Int.min.dividedReportingOverflow(by:-1)
 
 Peter
 ___
 swift-users mailing list
 swift-users@swift.org 
 https://lists.swift.org/mailman/listinfo/swift-users 
 
>>> 
>>> ___
>>> swift-users mailing list
>>> swift-users@swift.org 
>>> https://lists.swift.org/mailman/listinfo/swift-users 
>>> 
>> 
> 

___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


[swift-users] range(of:options:range:locale:) with partial ranges

2017-09-21 Thread Martin R via swift-users
The range(of:options:range:locale:) method of StringProtocol does not accept a 
partial range as search range. Example (Xcode 9, Swift 4):

let str = "foo"
let pos = str.startIndex
let r = str.range(of: "f", range: pos...)
// error: cannot convert value of type 'PartialRangeFrom'
// to expected argument type 'Range?'

Is that because it is an NSString method imported to Swift? Would it make sense 
to file an enhancement request?

Regards, Martin

___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] Simultaneous access to global tuple members

2017-08-11 Thread Martin R via swift-users
Thank you for the clarification.

> On 8. Aug 2017, at 18:39, Guillaume Lessard  
> wrote:
> 
> 
>> On Aug 8, 2017, at 09:10, Martin R  wrote:
>> 
>> In that example the tuple is a (stored) property of a class, not a global 
>> variable. And why does it crash for a global variable, but not for a local 
>> variable in a function?
> 
> In the case of a local variable in a function, the compiler can statically 
> prove that there is no simultaneous access, and using `swap` is allowed. With 
> a global variable, the compiler can’t statically prove exclusive access.
> (it seems silly with your simple example, but the system doesn’t try static 
> enforcement with global variables.)
> 
> Here’s another modification which traps at runtime:
> 
> ***
> import Dispatch
> 
> func foo()  {
>  var tuple = (1, 2)
> 
>  let q = DispatchQueue(label: "queue")
>  q.async { swap(, ) }
>  q.sync {}
> 
>  print(tuple)
> }
> 
> foo()
> ***
> 
> Guillaume Lessard
> 

___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


[swift-users] Simultaneous access to global tuple members

2017-08-08 Thread Martin R via swift-users
SE-0176 Enforce Exclusive Access to Memory 
(https://github.com/apple/swift-evolution/blob/master/proposals/0176-enforce-exclusive-access-to-memory.md)
 states that "Accesses to different stored properties of a struct or different 
elements of a tuple are allowed to overlap."

And indeed this compiles and runs as expected (Xcode 9 beta 4):

// main.swift

func foo()  {
var tuple = (1, 2)
swap(, )
print(tuple)
}

foo()

However, if the tuple is a global variable, it crashes with a runtime exception:

// main.swift

var tuple = (1, 2)
swap(, )
print(tuple)

Simultaneous accesses to 0x100401cb0, but modification requires exclusive 
access.
Previous access (a modification) started at tupleaccess`main + 76 
(0x115cc).
Current access (a modification) started at:
0tupleaccess0x000100335b60 
swift_beginAccess + 605
1tupleaccess0x00011580 main + 110
2libdyld.dylib  0x7fffa7284234 start + 1

Is there anything special with simultaneous access to members of a global 
tuple, or is this a bug?

Regards, Martin

___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] Exceptional values in the Comparable protocol

2017-07-11 Thread Martin R via swift-users
Thank you for the clarification!

> On 10. Jul 2017, at 23:29, Dave Abrahams via swift-users 
>  wrote:
> 
> 
> on Sun Jul 09 2017, Martin R  wrote:
> 
>> The Comparable protocol requires that < and == impose a strict total
>> order: exactly one of a==b, ab must hold for all values a and b
>> of a conforming type.
>> 
>> But it is also noted that a conforming type may contain a subset of
>> „exceptional values“ which do not take part in the strict total order
>> (such as FloatingPoint.nan).
>> 
>> What does that mean for functions taking comparable arguments, e.g.
>> 
>>func mySuperSort(a: inout [T]) { }
>> 
>> Can the function implementation assume that all values passed to it
>> take part in the strict total order? In other words: „exceptional
>> values“ must not be passed to the function?
> 
> Yes
> 
>> Or must the function take that case into account and must not assume
>> that exactly one of a==b, a> a>b holds for any arguments passed to it?
> 
> It need not, but it may do so as a matter of QOI (Quality Of
> Implementation).  It is a good idea to make such a function work for NaN
> if you can figure out what the semantics should be and it doesn't overly
> impact the performance of other important use cases.
> 
> Hope this helps,
> 
> -- 
> -Dave
> 
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] is this a defect in equatable for swift tuples?

2017-07-09 Thread Martin R via swift-users

> On 9. Jul 2017, at 21:20, David Baraff <davidbar...@gmail.com> wrote:
> 
> Nice: i hadn’t seen elementsEqual.
> 
>   (1) Why do you have to pass in “by: ==“ ?  is not that the default

There are two versions: One taking an explicit predicate, and another which 
requires sequences of Equatable elements. As observed earlier in this thread, 
an array of tuples is not Equatable.

> 
>   (2) not a big deal, but if the sequence type’s length can be determined a 
> priori (e.g. in the case of an Array, or perhaps a Collection if that has a 
> count member, haven’t checked) does the elementsEqual function short circuit 
> by first checking that the lengths are equal before beginning the loop?

As far as I can tell from the implementation at 
https://github.com/apple/swift/blob/master/stdlib/public/core/SequenceAlgorithms.swift.gyb#L292
 
<https://github.com/apple/swift/blob/master/stdlib/public/core/SequenceAlgorithms.swift.gyb#L292>
 , the length is not checked a-priori, so you might want to add that to your 
code:

class Tree : Equatable {
let rootData:Int = 0
let children:[(String, Tree)] = []

static public func ==(_ lhs:Tree, _ rhs:Tree) -> Bool {
return lhs.rootData == rhs.rootData &&
lhs.children.count == rhs.children.count &&
lhs.children.elementsEqual(rhs.children, by: ==)
}
}



> 
> But again, that’s a great one to know.
> 
>> On Jul 9, 2017, at 12:14 PM, Martin R via swift-users <swift-users@swift.org 
>> <mailto:swift-users@swift.org>> wrote:
>> 
>> 
>>> On 9. Jul 2017, at 21:00, Jens Persson via swift-users 
>>> <swift-users@swift.org <mailto:swift-users@swift.org>> wrote:
>>> 
>>> Since Array has .elementsEqual, another workaround (until conditional 
>>> conformance) is:
>>> 
>>> class Tree : Equatable {
>>> let rootData:Int
>>> let children:[(String, Tree)]
>>> 
>>> init(rootData: Int, children: [(String, Tree)]) {
>>> self.rootData = rootData
>>> self.children = children
>>> }
>>> static public func ==(_ lhs:Tree, _ rhs:Tree) -> Bool {
>>> return lhs.rootData == rhs.rootData &&
>>> lhs.children.elementsEqual(rhs.children, by: { (a: (String, 
>>> Tree), b: (String, Tree)) -> Bool in
>>> return a.0 == b.0 && a.1 == b.1
>>> })
>>> }
>>> }
>> 
>> 
>> Slightly simpler (since == is already defined for the tuples):
>> 
>> class Tree : Equatable {
>> let rootData:Int = 0
>> let children:[(String, Tree)] = []
>> 
>> static public func ==(_ lhs:Tree, _ rhs:Tree) -> Bool {
>> return lhs.rootData == rhs.rootData &&
>> lhs.children.elementsEqual(rhs.children, by: ==)
>> }
>> }
>> 
>> 
>>> 
>>> 
>>> On Sun, Jul 9, 2017 at 8:44 PM, David Sweeris <daveswee...@mac.com 
>>> <mailto:daveswee...@mac.com>> wrote:
>>> 
>>> On Jul 9, 2017, at 10:06, David Baraff via swift-users 
>>> <swift-users@swift.org <mailto:swift-users@swift.org>> wrote:
>>> 
>>>> 
>>>>> On Jul 9, 2017, at 8:27 AM, Jens Persson <j...@bitcycle.com 
>>>>> <mailto:j...@bitcycle.com>> wrote:
>>>>> 
>>>>> (Also, note that your implementation of == uses lhs === rhs thus will 
>>>>> only return true when lhs and rhs are the same instance of SomeClass.)
>>>> Of course — i threw that in just to make a simple example.
>>>> 
>>>> Followup question: what I really wanted to write was an == operator for a 
>>>> tree:
>>>> 
>>>> // silly tree, useful for nothing
>>>> class Tree : Equatable {
>>>>let rootData:Int
>>>>let children:[(String, Tree)]
>>>> 
>>>>static public func ==(_ lhs:Tree, _ rhs:Tree) {
>>>>return lhs.rootData == rhs.rootData && 
>>>> lhs.children == rhs.children   // sadly, this doesn’t 
>>>> compile
>>>>}
>>>> }
>>> 
>>> Right, the `==` func is *defined* for 2-element tuples where both elements 
>>> conform to `Equatable`, but that tuple type doesn't itself *conform* to 
>>> `Equatable`. So the`==` func that's defined on "Array where Element: 
>>> Equatable" can't see it.
>>> 
>>> We'd need both "conditional conformance" and "tuple conformance" in order 
>>> for that to Just Work.
>>> 
>>> - Dave Sweeris 
>>> 
>>> ___
>>> swift-users mailing list
>>> swift-users@swift.org <mailto:swift-users@swift.org>
>>> https://lists.swift.org/mailman/listinfo/swift-users 
>>> <https://lists.swift.org/mailman/listinfo/swift-users>
>> ___
>> swift-users mailing list
>> swift-users@swift.org <mailto:swift-users@swift.org>
>> https://lists.swift.org/mailman/listinfo/swift-users
> 

___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] is this a defect in equatable for swift tuples?

2017-07-09 Thread Martin R via swift-users

> On 9. Jul 2017, at 21:00, Jens Persson via swift-users 
>  wrote:
> 
> Since Array has .elementsEqual, another workaround (until conditional 
> conformance) is:
> 
> class Tree : Equatable {
> let rootData:Int
> let children:[(String, Tree)]
> 
> init(rootData: Int, children: [(String, Tree)]) {
> self.rootData = rootData
> self.children = children
> }
> static public func ==(_ lhs:Tree, _ rhs:Tree) -> Bool {
> return lhs.rootData == rhs.rootData &&
> lhs.children.elementsEqual(rhs.children, by: { (a: (String, 
> Tree), b: (String, Tree)) -> Bool in
> return a.0 == b.0 && a.1 == b.1
> })
> }
> }


Slightly simpler (since == is already defined for the tuples):

class Tree : Equatable {
let rootData:Int = 0
let children:[(String, Tree)] = []

static public func ==(_ lhs:Tree, _ rhs:Tree) -> Bool {
return lhs.rootData == rhs.rootData &&
lhs.children.elementsEqual(rhs.children, by: ==)
}
}


> 
> 
> On Sun, Jul 9, 2017 at 8:44 PM, David Sweeris  > wrote:
> 
> On Jul 9, 2017, at 10:06, David Baraff via swift-users  > wrote:
> 
>> 
>>> On Jul 9, 2017, at 8:27 AM, Jens Persson >> > wrote:
>>> 
>>> (Also, note that your implementation of == uses lhs === rhs thus will only 
>>> return true when lhs and rhs are the same instance of SomeClass.)
>> Of course — i threw that in just to make a simple example.
>> 
>> Followup question: what I really wanted to write was an == operator for a 
>> tree:
>> 
>> // silly tree, useful for nothing
>> class Tree : Equatable {
>>let rootData:Int
>>let children:[(String, Tree)]
>> 
>>static public func ==(_ lhs:Tree, _ rhs:Tree) {
>>  return lhs.rootData == rhs.rootData && 
>> lhs.children == rhs.children // sadly, this doesn’t 
>> compile
>>}
>> }
> 
> Right, the `==` func is *defined* for 2-element tuples where both elements 
> conform to `Equatable`, but that tuple type doesn't itself *conform* to 
> `Equatable`. So the`==` func that's defined on "Array where Element: 
> Equatable" can't see it.
> 
> We'd need both "conditional conformance" and "tuple conformance" in order for 
> that to Just Work.
> 
> - Dave Sweeris 
> 
> ___
> swift-users mailing list
> swift-users@swift.org 
> https://lists.swift.org/mailman/listinfo/swift-users 
> 
___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] is this a defect in equatable for swift tuples?

2017-07-09 Thread Martin R via swift-users
The == operator is defined for tuples with (up to 6) elements that conform to 
the Equatable protocol
(and < for tuples with Comparable elements):

class SomeClass: Equatable {
static public func ==(_ lhs:SomeClass, _ rhs:SomeClass) -> Bool {
return lhs === rhs
}
}

let c1 = SomeClass()
let c2 = SomeClass()

let t1 = ("abc", c1)
let t2 = ("abc", c2)

c1 == c2// legal
t1 == t2// legal

The existence of a == operator alone, without declaring protocol conformance, 
is not sufficient.


> On 9. Jul 2017, at 17:11, David Baraff via swift-users 
>  wrote:
> 
> Given 2-tuples of type (T1, T2), you should be able to invoke the == operator 
> if you could on both types T1 and T2, right?  i.e.
> 
> (“abc”, 3) == (“abc”, 4)  // legal
> 
> but:
> 
> class SomeClass {
> static public func ==(_ lhs:SomeClass, _ rhs:SomeClass) -> Bool {
> return lhs === rhs
> }
> }
> 
> let c1 = SomeClass()
> let c2 = SomeClass()
> 
> let t1 = ("abc", c1)
> let t2 = ("abc", c2)
> 
> c1 == c2  // legal
> t1 == t2  // illegal
> 
> 
> 
> 
> Why is t1 == t2 not legal given that c1 == c2 IS legal?
> 
> 
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


[swift-users] Exceptional values in the Comparable protocol

2017-07-09 Thread Martin R via swift-users
The Comparable protocol requires that < and == impose a strict total order: 
exactly one of a==b, ab must hold for all values a and b of a conforming 
type.

But it is also noted that a conforming type may contain a subset of 
„exceptional values“ which do not take part in the strict total order (such as 
FloatingPoint.nan).

What does that mean for functions taking comparable arguments, e.g.

func mySuperSort(a: inout [T]) { }

Can the function implementation assume that all values passed to it take part 
in the strict total order? In other words: „exceptional values“ must not be 
passed to the function?

Or must the function take that case into account and must not assume that 
exactly one of a==b, ab holds for any arguments passed to it?

Regards, Martin




___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


[swift-users] Passing Data to a f(void *) function

2017-06-30 Thread Martin R via swift-users
I have a C function 

void myfunc(const void *ptr);

which is imported to Swift as

func myfunc(_ ptr: UnsafeRawPointer!)

This compiles and runs without problems:

let data = Data(bytes: [1, 2, 3, 4])
data.withUnsafeBytes { (ptr) in myfunc(ptr) } // (A)

and the type of `ptr` is inferred as `UnsafePointer`. But adding an 
explicit type
annotation produces a compiler warning:

data.withUnsafeBytes { (ptr: UnsafePointer) in myfunc(ptr) } // (B)
// warning: UnsafePointer has been replaced by UnsafeRawPointer

which is understandable in the view of "SE-0107 UnsafeRawPointer API".

The "Fix-it" replaces `UnsafePointer` by `UnsafeRawPointer`, and that 
does not
compile anymore:

data.withUnsafeBytes { (ptr: UnsafeRawPointer) in myfunc(ptr) } // (C)
// error: cannot convert value of type 'Void' to closure result type '_'

because there is no `withUnsafeBytes()` method taking a 
`(UnsafeRawPointer)->ResultType`
closure.


My questions are:

1. Why are (A) and (B) treated differently?

2. Is (A) "legal", or should one use some non-void pointer

data.withUnsafeBytes { (ptr: UnsafePointer) in myfunc(ptr) } // (D)

   (which feels wrong to me because it is converted back to a void pointer when
   calling the function).

3. Or should there be a `withUnsafeRawPointer()` method which makes (C) compile 
as

  data.withUnsafeRawBytes { (ptr: UnsafeRawPointer) in myfunc(ptr) }

   This would also allow to access the data at byte offsets more easily, e.g.

   data.withUnsafeRawBytes { ptr in
   let u16 = ptr.load(fromByteOffset: 4, as: UInt16.self)
   }

   Does that makes sense?

Regards, Martin








 
___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] Optional binding with non-optional expression

2017-06-04 Thread Martin R via swift-users
I don’t think that explains it (or perhaps I did not understand your response 
correctly).

Here is the same issue with a custom type (which does not have a failable 
initializer):

   struct A { }

   if let a = A() { }
   // error: initializer for conditional binding must have Optional type, not 
'A' 

   if let a: A = A() { }
   // warning: non-optional expression of type 'A' used in a check for optionals


> Am 02.06.2017 um 15:49 schrieb Zhao Xin <owe...@gmail.com>:
> 
> I think it did an unnecessary implicitly casting. For example,
> 
> let y = Int(exactly: 5)
> print(type(of:y)) // Optional
> 
> You code equals to
> 
> if let y:Int = Int(exactly: 5) { }
> 
> However, I don't know why it did that. Maybe because of type inferring?
> 
> Zhaoxin
> 
> On Fri, Jun 2, 2017 at 8:40 PM, Martin R via swift-users 
> <swift-users@swift.org> wrote:
> This following code fails to compile (which is correct, as far as I can judge 
> that):
> 
>if let x = 5 { }
>// error: initializer for conditional binding must have Optional type, not 
> 'Int'
> 
> But why is does it compile (with a warning) if an explicit type annotation is 
> added?
> 
>if let y: Int = 5 { }
>// warning: non-optional expression of type 'Int' used in a check for 
> optionals
> 
> Tested with Xcode 8.3.2 and both the build-in Swift 3.1 toolchain and the 
> Swift 4.0 snapshot from May 25, 2017.
> 
> I am just curious and would like to understand if there is fundamental 
> difference between those statements.
> 
> Regards, Martin
> 
> 
> 
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users
> 
> 

___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


[swift-users] Optional binding with non-optional expression

2017-06-02 Thread Martin R via swift-users
This following code fails to compile (which is correct, as far as I can judge 
that):

   if let x = 5 { }
   // error: initializer for conditional binding must have Optional type, not 
'Int'

But why is does it compile (with a warning) if an explicit type annotation is 
added?

   if let y: Int = 5 { }
   // warning: non-optional expression of type 'Int' used in a check for 
optionals

Tested with Xcode 8.3.2 and both the build-in Swift 3.1 toolchain and the Swift 
4.0 snapshot from May 25, 2017.

I am just curious and would like to understand if there is fundamental 
difference between those statements.

Regards, Martin


___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] Splitting a string into "natural/visual character" components?

2017-05-12 Thread Martin R via swift-users
The enumerateSubstrings method of (NS)String has a 
.byComposedCharacterSequences option which causes Emoji sequences like 
"‍‍‍" to be treated as a single unit:

func f(_ s: String) -> [String] {
var a: [String] = []
s.enumerateSubstrings(in: s.startIndex.., Emoji sequences are considered as a 
single grapheme cluster in Unicode 9, which means that you can simply do 
something like

Array("‍‍‍‍♀️".characters)

once Unicode 9 is adopted in Swift.

Regards, Martin


> On 12. May 2017, at 10:43, Jens Persson via swift-users 
>  wrote:
> 
> I want a function f such that:
> 
> f("abc") == ["a", "b", "c"]
> 
> f("café") == ["c", "a", "f", "é"]
> 
> f("‍‍‍‍♀️") == ["‍‍‍", "‍♀️"]
> 
> I'm not sure if the last example renders correctly by mail for everyone but 
> the input String contains these _two_ "natural/visual characters":
> (1) A family emoji
> (2) a construction worker (woman, with skin tone modifier) emoji.
> and the result is an Array of two strings (one for each emoji).
> 
> The first two examples are easy, the third example is the tricky one.
> 
> Is there a (practical) way to do this (in Swift 3)?
> 
> /Jens
> 
> 
> 
> PS
> 
> It's OK if the function has to depend on eg a graphics context etc.
> (I tried writing a function so that it extracts the glyphs, using 
> NSTextStorage, NSLayoutManager and the AppleColorEmoji font, but it says that 
> "‍‍‍‍♀️" contains 18(!) glyphs, whereas eg "café" contains 4 as 
> expected.)
> 
> If the emojis of the third example doesn't look like they should in this 
> mail, here is another way to write the exact same example using only simple 
> text:
> 
> let inputOfThirdExample = 
> "\u{1F468}\u{200D}\u{1F469}\u{200D}\u{1F467}\u{200D}\u{1F466}\u{1F477}\u{1F3FE}\u{200D}\u{2640}\u{FE0F}"
> 
> let result = f(inputOfThirdExample)
> 
> let expectedResult = 
> ["\u{1F468}\u{200D}\u{1F469}\u{200D}\u{1F467}\u{200D}\u{1F466}", 
> "\u{1F477}\u{1F3FE}\u{200D}\u{2640}\u{FE0F}"]
> 
> print(result.elementsEqual(result)) // Should print true
> 
> 
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] Error creating empty array of chained associated type

2017-04-29 Thread Martin R via swift-users
That seems to be a known problem: https://bugs.swift.org/browse/SR-773 
 

> On 29. Apr 2017, at 22:38, Nevin Brackett-Rozinsky via swift-users 
>  wrote:
> 
> I’ve stumbled upon an odd situation where Swift gives a compiler error if I 
> do things directly, but works properly with no error if I first create a 
> typealias. Here is a stripped-down example:
> 
> protocol P {
> associatedtype C: Collection
> }
> 
> extension P {
> func emptyArray() -> [C.Iterator.Element] {
> return [C.Iterator.Element]()   // Error
> }
> }
> 
> The “return” line gives the error “Cannot call value of non-function type 
> '[Self.C.Iterator.Element.Type]'” in Xcode 8.3.2. However, if we replace that 
> function with a seemingly-equivalent version that uses a typealias, there is 
> no error:
> 
> extension P {
> func emptyArray() -> [C.Iterator.Element] {
> typealias E = C.Iterator.Element
> return [E]()// Works
> }
> }
> 
> Is this a known bug?
> 
> Nevin
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] Guarantees of Tuples as Fixed Sized (stack allocated) Arrays

2017-04-28 Thread Martin R via swift-users
As far as I know, the only guarantee is made for structures imported from C. 
From 
https://lists.swift.org/pipermail/swift-users/Week-of-Mon-20160516/001968.html 

 :

   Swift structs have unspecified layout. If you depend on a specific layout, 
you should define the struct in C and import it into Swift for now.

and from 
https://lists.swift.org/pipermail/swift-users/Week-of-Mon-20160516/001980.html 

 :

   That's not necessary. You can leave the struct defined in C and import it 
into Swift. Swift will respect C's layout.

Regards, Martin


> On 28. Apr 2017, at 13:03, Johannes Weiss via swift-users 
>  wrote:
> 
> Hi swift-users,
> 
> (sorry for the cross post to swift-dev, but wasn't sure where it belongs)
> 
> I tried to find guarantees about the memory layout Swift tuples but couldn't 
> find anything. The reason I ask is because I'd like to use them as fixed 
> sized (stack allocated) arrays. I'm pretty sure they're actually not 
> guaranteed to be stack allocated but highly likely I assume :).
> 
> Am I correct in assuming that
> 
>let swift_events: (kevent, kevent) = ...
> 
> has the same memory layout as
> 
>struct kevent c_events[2] = ...
> 
> ? In other words, is this legal:
> 
>var events = (kevent(), kevent())
>withUnsafeMutableBytes(of: ) { event_ptr in
>precondition(MemoryLayout.size * 2 == event_ptr.count)
>if let ptr = event_ptr.baseAddress?.bindMemory(to: kevent.self, 
> capacity: 2) {
>return kevent(someFileDescriptor, ptr, 2, ptr, 2, nil)
>}
>}
> 
> I'm assuming yes but I'd like to make sure.
> 
> Many thanks,
>  Johannes
> 
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] String init from Int8 tuple?

2017-04-19 Thread Martin R via swift-users
This reminds me of my previous question 
https://lists.swift.org/pipermail/swift-users/Week-of-Mon-20170220/004841.html 


> Is that simplified guaranteed to work? The Swift book says that
> 
> > As an optimization, when the argument is a value stored at a physical 
> > address in memory, the same memory location is used both inside and outside 
> > the function body.
> 
> but also 
> 
> > Write your code using the model given by copy-in copy-out, without 
> > depending on the call-by-reference optimization, so that it behaves 
> > correctly with or without the optimization.
> 
> If `tmp.0` is copied to a separate location then `String(cString: )` 
> would not work correctly, or would it?

to which Quinn responded 
https://lists.swift.org/pipermail/swift-users/Week-of-Mon-20170220/004842.html 


> Based on a previous conversation I had with the Swift folks about this, yes.
> 
> However, I don’t work on the compiler so it’s possible I misunderstood.  
> Perhaps someone from SwiftLand™ will chime in here.

Some authoritative response from SwiftLand™ would be much appreciated.

Regards, Martin


> On 19. Apr 2017, at 09:16, Quinn The Eskimo! via swift-users 
>  wrote:
> 
> 
> On 19 Apr 2017, at 02:11, Rick Mann via swift-users  
> wrote:
> 
>> In my C-interop, I have a need to do this a lot:
> 
> I think you’re working too hard here.  Try this:
> 
> func callbackFailed(info inInfo: lgs_result_info_t) {
>   var m = inInfo.message
>   let message = String(cString: )
>   debugLog("Failed: \(message)")
> }
> 
> Alas, you still need to do the copy in order to take the address of `m`.
> 
> Share and Enjoy
> --
> Quinn "The Eskimo!"
> Apple Developer Relations, Developer Technical Support, Core OS/Hardware
> 
> 
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


[swift-users] UTF-16 string index can be incremented beyond end index

2017-03-16 Thread Martin R via swift-users
The index of the UTF-16 view of a string can be incremented beyond the end 
index:

let s = "foo"

let u16 = s.utf16
let i16 = u16.index(u16.endIndex, offsetBy: 99, limitedBy: u16.endIndex)

print(i16 as Any)
// Optional(Swift.String.UTF16View.Index(_offset: 102))

I wonder if this behaviour is intended or if I should file a bug report.

All other string views behave as I would expect it:

let cs = s.characters
let ic = cs.index(cs.endIndex, offsetBy: 99, limitedBy: cs.endIndex)
print(ic as Any) // nil

let u8 = s.utf8
let i8 = u8.index(u8.endIndex, offsetBy: 99, limitedBy: u8.endIndex)
print(i8 as Any) // nil

let us = s.unicodeScalars
let iu = us.index(us.endIndex, offsetBy: 99, limitedBy: us.endIndex)
print(iu as Any) // nil

Tested with Xcode 8.2.1 and 8.3 beta 4.

Regards, Martin

___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] Using withUnsafePointer on char arrays within C structs

2017-02-23 Thread Martin R via swift-users
Is that simplified guaranteed to work? The Swift book says that

> As an optimization, when the argument is a value stored at a physical address 
> in memory, the same memory location is used both inside and outside the 
> function body.

but also 

> Write your code using the model given by copy-in copy-out, without depending 
> on the call-by-reference optimization, so that it behaves correctly with or 
> without the optimization.

If `tmp.0` is copied to a separate location then `String(cString: )` 
would not work correctly, or would it?

Thank you in advance,
Martin


> On 23 Feb 2017, at 09:33, Quinn The Eskimo! via swift-users 
>  wrote:
> 
> 
> On 22 Feb 2017, at 22:16, Russell Finn via swift-users 
>  wrote:
> 
>> … is (2) the best I can do for now?
> 
> Yes.
> 
> btw You can simplify the code to this:
> 
>var description: String {
>var tmp = self.path
>return String(cString: )
>}
> 
> but it still needs that copy.
> 
>> And is this the sort of issue that the Ownership Manifesto is designed to 
>> address?
> 
> I’m not sufficiently up to speed on that topic to answer this.  Sorry.
> 
> Share and Enjoy
> --
> Quinn "The Eskimo!"
> Apple Developer Relations, Developer Technical Support, Core OS/Hardware
> 
> 
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] UnsafePointer to UInt64

2017-02-16 Thread Martin R via swift-users
// Int to pointer:
let ptr = UnsafePointer(bitPattern: 123)!
print(ptr) // 0x007b

// Pointer to Int:
let int = Int(bitPattern: ptr)
print(int) // 123

Int has the same size as a pointer on both 32-bit and 64-bit platforms.

Regards, Martin

> On 16 Feb 2017, at 14:27, Rien via swift-users  wrote:
> 
> What would be the easiest (and fastest) way to convert a pointer to an 
> (unsigned)integer?
> 
> Ptr -> String -> Int
> 
> seems a bit cumbersome to me :-)
> 
> Regards,
> Rien
> 
> Site: http://balancingrock.nl
> Blog: http://swiftrien.blogspot.com
> Github: http://github.com/Balancingrock
> Project: http://swiftfire.nl
> 
> 
> 
> 
> 
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


[swift-users] Why do collections use the debugDescription on their elements?

2017-01-05 Thread Martin R via swift-users
I wonder why the description method of collections use the debugDescription 
method to print their elements, and not the description method. Example:

let s = "a\"b"
print(s) // a"b
print(s.debugDescription) // "a\"b"

let x = 1.1
print(x) // 1.1
print(x.debugDescription) // 1.1001

let d = [ s : x ]
print(d) // ["a\"b": 1.1001]


- The embedded quotation mark is printed as " in print(s), but as \" in 
print(d).
- The floating point number is printed with a higher precision in the 
dictionary description.

The same happens with `Array`, `Set` and also `Optional`. Is there a special 
reason? It seems unnecessary and a possible cause for confusion to me.

Regards,
Martin

___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


[swift-users] Access level of members defined in an extension

2016-12-09 Thread Martin R via swift-users
I have a question about the relationship between the access level of an 
extension
and the access level of members defined in that extension.

The "Access Control" chapter in "The Swift Programming Language" states about 
extensions: 

   Alternatively, you can mark an extension with an explicit access-level 
modifier
   (for example, private extension) to set a new default access level for all 
members
   defined within the extension. This new default can still be overridden 
within the
   extension for individual type members.
   
But apparently the access level of a member can only be equal to or lower than 
the
access of the extension in which it is defined, and the compiler warns if I try 
to
increase it:

private class MyClass {
public func foo() { } // No warning
}

private extension MyClass {
public func bar() { } // warning: declaring a public instance method in 
a private extension
}
 
There is no warning for `func foo` which is defined in the class itself, only 
for
`func bar` which is defined in an extension.

SE-0117 states that 

   ... the true access level of a type member is computed as the minimum of the 
true
   access level of the type and the declared access level of the member.

My questions are:

- Does a similar statement hold for members defined in an extension, i.e. the 
true
  access level is the minimum of the declared access level and the access level 
of
  the extension in which it is defined? In other words, I can only lower the 
default
  access level of the extension, but not increase it.
- Why does the compiler warn if I define a member with a higher access level in 
an
  extension, but not if I do the same in the main class definition?

Regards,
Martin

___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] How to dispatch on the size of Int?

2016-11-23 Thread Martin R via swift-users
Yes, I had forgotten about that, thank you! That would satisfy all criteria. 
And with 

func foo(value: Int) {
#if arch(i386) || arch(arm) 
foo_impl(value: Int32(value))
#elseif arch(x86_64) || arch(arm64) 
foo_impl(value: Int64(value))
#endif
}

it should be „future-safe“, i.e. fail to compile on a new platform. (I would 
still prefer a solution which does not require me to know about all possible 
processor architectures.)

> Am 23.11.2016 um 23:06 schrieb Hooman Mehr <hoo...@mac.com>:
> 
> func foo_impl(value: Int32) { /* ... */ }
> func foo_impl(value: Int64) { /* ... */ }
> 
> func foo(value: Int) {
> #if arch(i386) || arch(arm)
> foo_impl(value: Int32(value))
> #else
> foo_impl(value: Int64(value))
> #endif
> }
> 
> 
>> On Nov 23, 2016, at 1:31 PM, Martin R via swift-users 
>> <swift-users@swift.org> wrote:
>> 
>> I wonder what the best way would be to call a specialized function dependent 
>> on the size of `Int`. Let's say that I have two implementations
>> 
>>func foo_impl(value: Int32) { /* ... */ }
>>func foo_impl(value: Int64) { /* ... */ }
>> 
>> and I want 
>> 
>>func foo(value: Int)
>> 
>> to call the "right one" of them, according to the architecture (32-bit or 
>> 64-bit).
>> 
>>func foo(value: Int) { foo_impl(value: value) }
>> 
>> does not compile. (I assume that is because `Int` is not a type alias to 
>> `Int32` or `Int64` but an independent type.)
>> 
>> This works: 
>> 
>>func foo1(value: Int) {
>>if MemoryLayout.size == 4 {
>>foo_impl(value: Int32(value))
>>} else {
>>foo_impl(value: Int64(value))
>>}
>>}
>> 
>> or
>> 
>>func foo2(value: Int) {
>>switch MemoryLayout.size {
>>case 4: foo_impl(value: Int32(value))
>>case 8: foo_impl(value: Int64(value))
>>default:
>>abort()
>>}
>>}
>> 
>> But a typo in the constants would go unnoticed and just call the wrong 
>> function, or cause a runtime error instead of a compile-time error. And 
>> perhaps `Int` can be an 128-bit integer in the future? The compiler would 
>> not warn that the code needs to be updated.
>> 
>> This seems to be more promising:
>> 
>>func foo3(value: Int) {
>>switch (__WORDSIZE) {
>>case 32: foo_impl(value: Int32(value)) // Warning: Will never be 
>> executed
>>case 64: foo_impl(value: Int64(value))
>>}
>>}
>> 
>> Apparently the compiler "knows" which case will be executed, `foo3` does not 
>> compile if there is no case matching actual integer size. But there is 
>> always an annoying warning for the unused case. And I am not sure if it is 
>> guaranteed that __WORDSIZE is the number of bits in an `Int`.
>> 
>> So my question is: What would be the best way to dispatch dependent on the 
>> size of `Int`, such that
>> 
>> - The compiler checks the correctness.
>> - The compiler optimizes the code so that no runtime check is done.
>> - No warnings are produced.
>> 
>> If `Int` had a `native` property like `CGFloat` then I could simply call
>> 
>>func foo(value: Int) { foo_impl(value: value.native) }
>> 
>> but I could not find such a property. (Would that be a reasonable thing to 
>> ask on swift-evolution?)
>> 
>> Background: I am asking this just out of curiosity, but the question came up 
>> when looking at the `hash_combine` function in the Boost library:
>> 
>>  http://www.boost.org/doc/libs/1_62_0/boost/functional/hash/hash.hpp 
>> 
>> with quite different implementations 
>> 
>>inline void hash_combine_impl(boost::uint32_t& h1, boost::uint32_t k1)
>>inline void hash_combine_impl(boost::uint64_t& h, boost::uint64_t k)
>> 
>> and I wondered how this would be done in Swift.
>> 
>> Regards, 
>> Martin
>> 
>> 
>> ___
>> swift-users mailing list
>> swift-users@swift.org
>> https://lists.swift.org/mailman/listinfo/swift-users
> 

___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


[swift-users] How to dispatch on the size of Int?

2016-11-23 Thread Martin R via swift-users
I wonder what the best way would be to call a specialized function dependent on 
the size of `Int`. Let's say that I have two implementations

func foo_impl(value: Int32) { /* ... */ }
func foo_impl(value: Int64) { /* ... */ }

and I want 

func foo(value: Int)

to call the "right one" of them, according to the architecture (32-bit or 
64-bit).

func foo(value: Int) { foo_impl(value: value) }
   
does not compile. (I assume that is because `Int` is not a type alias to 
`Int32` or `Int64` but an independent type.)

This works: 

func foo1(value: Int) {
if MemoryLayout.size == 4 {
foo_impl(value: Int32(value))
} else {
foo_impl(value: Int64(value))
}
}

or

func foo2(value: Int) {
switch MemoryLayout.size {
case 4: foo_impl(value: Int32(value))
case 8: foo_impl(value: Int64(value))
default:
abort()
}
}

But a typo in the constants would go unnoticed and just call the wrong 
function, or cause a runtime error instead of a compile-time error. And perhaps 
`Int` can be an 128-bit integer in the future? The compiler would not warn that 
the code needs to be updated.

This seems to be more promising:

func foo3(value: Int) {
switch (__WORDSIZE) {
case 32: foo_impl(value: Int32(value)) // Warning: Will never be 
executed
case 64: foo_impl(value: Int64(value))
}
}

Apparently the compiler "knows" which case will be executed, `foo3` does not 
compile if there is no case matching actual integer size. But there is always 
an annoying warning for the unused case. And I am not sure if it is guaranteed 
that __WORDSIZE is the number of bits in an `Int`.
 
So my question is: What would be the best way to dispatch dependent on the size 
of `Int`, such that

- The compiler checks the correctness.
- The compiler optimizes the code so that no runtime check is done.
- No warnings are produced.

If `Int` had a `native` property like `CGFloat` then I could simply call

func foo(value: Int) { foo_impl(value: value.native) }

but I could not find such a property. (Would that be a reasonable thing to ask 
on swift-evolution?)

Background: I am asking this just out of curiosity, but the question came up 
when looking at the `hash_combine` function in the Boost library:

  http://www.boost.org/doc/libs/1_62_0/boost/functional/hash/hash.hpp 
  
with quite different implementations 

inline void hash_combine_impl(boost::uint32_t& h1, boost::uint32_t k1)
inline void hash_combine_impl(boost::uint64_t& h, boost::uint64_t k)

and I wondered how this would be done in Swift.

Regards, 
Martin


___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] How to merge two dictionaries?

2016-11-11 Thread Martin R via swift-users
Nate Cook proposed merging dictionary initializers (with optional conflict 
resolution) to be added to the standard library:

  SE-0100 Add sequence-based initializers and merge methods to Dictionary
  
https://github.com/apple/swift-evolution/blob/master/proposals/0100-add-sequence-based-init-and-merge-to-dictionary.md

Martin


> On 11 Nov 2016, at 09:14, Ray Fix via swift-users  
> wrote:
> 
> Hi Mr Bee,
> 
> The reason I don’t think it is provided is because it is difficult to know 
> what to do when keys collide.  You could easily write such a thing and decide 
> your own policy.  For example:
> 
> let d1 = ["Apples": 20, "Oranges": 13]
> let d2 = ["Oranges": 3, "Cherries": 9]
> 
> extension Dictionary {
> func merged(with another: [Key: Value]) -> [Key: Value] {
> var result = self
> for entry in another {
> result[entry.key] = entry.value
> }
> return result
> }
> }
> 
> let result = d1.merged(with: d2)
> 
> 
>> On Nov 11, 2016, at 12:05 AM, Mr Bee via swift-users  
>> wrote:
>> 
>> Hi,
>> 
>> I'm using Swift v3 on an El Capitan machine. I want to merge a dictionary 
>> into another compatible dictionary. However, I couldn't find addEntries 
>> function in the dictionary instance, like it was on NSMutableDictionary 
>> (https://developer.apple.com/reference/foundation/nsmutabledictionary). 
>> 
>> Does that mean that Swift standard library won't provide such similar 
>> function for native Swift dictionary? Or is there any other way of doing 
>> that natively? I mean using the built-in Swift's native dictionary function 
>> (https://developer.apple.com/reference/swift/dictionary), no need to write a 
>> custom function, or bridging to NSMutableDictionary.
>> 
>> Thank you.
>> 
>> Regards,
>> 
>> –Mr Bee
>> 
>> ___
>> swift-users mailing list
>> swift-users@swift.org
>> https://lists.swift.org/mailman/listinfo/swift-users
> 
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] Type inference when assigning the result of reduce to a dictionary

2016-10-04 Thread Martin R via swift-users

> On 4 Oct 2016, at 21:42, Joe Groff <jgr...@apple.com> wrote:
> 
> 
>> On Oct 4, 2016, at 5:20 AM, Martin R via swift-users <swift-users@swift.org> 
>> wrote:
>> 
>> I noticed the following when assigning the result of `reduce()` to a 
>> dictionary:
>> 
>>   let array = [1, 2, 3]
>>   var dict: [Int: Int] = [:]
>>   dict[0] = array.reduce(0, { $0 + $1 }) // (A)
>>   // error: binary operator '+' cannot be applied to operands of
>> type 'Int?' and 'Int'
>>   // dict[0] = array.reduce(0, { $0 + $1 })
>>   // ~~ ^ ~~
>> 
>> It seems that the compiler tries to make the RHS an `Int?` and
>> therefore infers the type of the initial value `0` and the
>> accumulating value `$0` as `Int?`.
>> 
>> That is in some sense correct, since the dictionary subscript setter
>> takes an optional as parameter, in this case `Int?`.
>> 
>> However, the code compiles (and runs as expected) if the trailing
>> closure syntax is used:
>> 
>>   dict[0] = array.reduce(0) { $0 + $1 } // (B)
>> 
>> and also if the initial value is given as `0` instead of `Int(0)`:
>> 
>>   dict[0] = array.reduce(Int(0), { $0 + $1 }) // (C)
>> 
>> My questions are:
>> - Should (A) compile?
>> - Why does it make a difference if the trailing closure syntax is used
>> (A vs. B)?
>> - Why does it make a difference if the initial value is given as `0`
>> or `Int(0)` (A vs. C)?
> 
> No good reason. Got time to file a bug?
> 
> -Joe

Done: https://bugs.swift.org/browse/SR-2853 .


___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


[swift-users] Type inference when assigning the result of reduce to a dictionary

2016-10-04 Thread Martin R via swift-users
I noticed the following when assigning the result of `reduce()` to a dictionary:

let array = [1, 2, 3]
var dict: [Int: Int] = [:]
dict[0] = array.reduce(0, { $0 + $1 }) // (A)
// error: binary operator '+' cannot be applied to operands of
type 'Int?' and 'Int'
// dict[0] = array.reduce(0, { $0 + $1 })
// ~~ ^ ~~

It seems that the compiler tries to make the RHS an `Int?` and
therefore infers the type of the initial value `0` and the
accumulating value `$0` as `Int?`.

That is in some sense correct, since the dictionary subscript setter
takes an optional as parameter, in this case `Int?`.

However, the code compiles (and runs as expected) if the trailing
closure syntax is used:

dict[0] = array.reduce(0) { $0 + $1 } // (B)

and also if the initial value is given as `0` instead of `Int(0)`:

dict[0] = array.reduce(Int(0), { $0 + $1 }) // (C)

My questions are:
- Should (A) compile?
- Why does it make a difference if the trailing closure syntax is used
(A vs. B)?
- Why does it make a difference if the initial value is given as `0`
or `Int(0)` (A vs. C)?

Regards,
Martin
___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] NSData vs Data write to string differently?

2016-09-22 Thread Martin R via swift-users
I had filed a related bug

  https://bugs.swift.org/browse/SR-2514
  Add a "hex dump" method to `Data`

as a result of the discussion starting at

  https://lists.swift.org/pipermail/swift-users/Week-of-Mon-20160822/003035.html

Martin


> On 23 Sep 2016, at 03:47, Joe Groff via swift-users  
> wrote:
> 
> 
>> On Sep 22, 2016, at 4:04 PM, Shawn Erickson via swift-users 
>>  wrote:
>> 
>> In general you shouldn't depend on what description returns for classes, 
>> etc. outside of your control unless it is documented (e.g. part of the API 
>> contract). If you want a specific output you should code up something to 
>> format the output as you need.
> 
> This is good advice, but the printing behavior of Data nonetheless strikes me 
> as a bug. NSData's printing behavior seems much more useful than Data's. If 
> either of you have a moment, would you be able to file a bug about this?
> 
> -Joe
> 
>> -Shawn
>> 
>> On Thu, Sep 22, 2016 at 3:33 PM Robert Nikander via swift-users 
>>  wrote:
>> Hi,
>> 
>> I’ve run into a problem when updating to new Swift in Xcode 8. There was 
>> some NSData in a string like this:
>> 
>>“ … \(data) … “
>> 
>> It changed to type `Data`, and the string went from hexadecimal bytes to 
>> writing “20 bytes”. I’m doing a quick bug fix app release now. I can’t 
>> remember if Xcode auto converted this for me. I thought it did.  ?  Either 
>> way… seems like they should behave the same here, no?
>> 
>> Rob
>> 
>> 
>> ___
>> swift-users mailing list
>> swift-users@swift.org
>> https://lists.swift.org/mailman/listinfo/swift-users
>> ___
>> swift-users mailing list
>> swift-users@swift.org
>> https://lists.swift.org/mailman/listinfo/swift-users
> 
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] How to create an uninitialized pointer in Swift 3

2016-09-16 Thread Martin R via swift-users
In Swift 3, COpaquePointer was renamed to OpaquePointer, and nullable pointers 
are represented by optionals:

  SE-0055 – Make unsafe pointer nullability explicit using Optional
  
https://github.com/apple/swift-evolution/blob/master/proposals/0055-optional-unsafe-pointers.md

So the following should work in Swift 3:

  var cublasHandle: OpaquePointer?
  let status = cublasCreate_v2()

Martin

> On 15 Sep 2016, at 23:38, Lane Schwartz via swift-users 
>  wrote:
> 
> In Swift 2.2, I could do the following:
> 
> var cublasHandle : COpaquePointer = nil
> let status = cublasCreate_v2()
> 
> Where cublasCreate_v2 is a C function that takes a pointer, and then 
> initializes some memory at that address.
> 
> I haven't been able to figure out an equivalent in Swift 3. Any suggestions, 
> especially to documentation, would be greatly appreciated.
> 
> Thanks,
> Lane
> 
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] No hex dump anymore in Data description

2016-08-29 Thread Martin R via swift-users
Done: https://bugs.swift.org/browse/SR-2514 .

Martin
(Resent as text mail. I apologize for the previous HTML-only mail.)

2016-08-29 10:51 GMT+02:00 Quinn "The Eskimo!" via swift-users
<swift-users@swift.org>:
>
> On 27 Aug 2016, at 07:45, Martin R via swift-users <swift-users@swift.org> 
> wrote:
>
>> Is it intentional that the description method of Data returns only the 
>> number of bytes, but not a hex dump of the contents (as NSData did)?
>
> It doesn’t really matter if it was intentional or not; if it’s annoying then 
> you should file a bug about it anyway.  [I’d file my own but it’d go into 
> Radar and you wouldn’t be able to see it )-: ]
>
> Share and Enjoy
> --
> Quinn "The Eskimo!"<http://www.apple.com/developer/>
> Apple Developer Relations, Developer Technical Support, Core OS/Hardware
___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] No hex dump anymore in Data description

2016-08-29 Thread Martin R via swift-users
Done: https://bugs.swift.org/browse/SR-2514 .MartinAm 29.08.2016 um 10:51 schrieb Quinn The Eskimo! via swift-users <swift-users@swift.org>:On 27 Aug 2016, at 07:45, Martin R via swift-users <swift-users@swift.org> wrote:Is it intentional that the description method of Data returns only the number of bytes, but not a hex dump of the contents (as NSData did)? It doesn’t really matter if it was intentional or not; if it’s annoying then you should file a bug about it anyway.  [I’d file my own but it’d go into Radar and you wouldn’t be able to see it )-: ]Share and Enjoy--Quinn "The Eskimo!"    Apple Developer Relations, Developer Technical Support, Core OS/Hardware___swift-users mailing listswift-users@swift.orghttps://lists.swift.org/mailman/listinfo/swift-users___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


[swift-users] No hex dump anymore in Data description

2016-08-27 Thread Martin R via swift-users
Is it intentional that the description method of Data returns only the number 
of bytes, but not a hex dump of the contents (as NSData did)? 

let data = Data(bytes: [1, 2, 3])
print(data) // 3 bytes
print(data.debugDescription) // 3 bytes

Of course I can bridge back to NSData:

print(data as NSData) // <010203>

But other collection types (Array, Dictionary, Set) print all their elements, 
regardless of the size of the collection.

For debugging purposes, the "old behavior" of returning a hex dump would be 
useful.

Martin

___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


[swift-users] Pointer conversions between different sockaddr types

2016-08-17 Thread Martin R via swift-users
I am trying to figure out how to work correctly with the new UnsafeRawPointer 
API (from 
https://github.com/apple/swift-evolution/blob/master/proposals/0107-unsaferawpointer.md
 ).

Here my concrete example: The connect() system call takes a (const struct 
sockaddr *address) parameter, but one actually passes the address of a struct 
sockaddr_in or sockaddr_in6 (or ...).

In Swift 2.2 this could be done as

var addr = sockaddr_in() // or sockaddr_in6()
// fill addr fields ...
let sock = socket(PF_INET, SOCK_STREAM, 0)

let result = withUnsafePointer() {
connect(sock, UnsafePointer($0), socklen_t(strideofValue(addr)))
}

With the latest Swift from Xcode 8 beta 6, unsafe pointers cannot be simply 
initialized from a different kind of unsafe pointer anymore. I came up with two 
different solutions: 

let result = withUnsafePointer(to: ) {
connect(sock,
UnsafeRawPointer($0).assumingMemoryBound(to: sockaddr.self),
socklen_t(MemoryLayout.stride))
}

or

let result = withUnsafePointer(to: ) {
$0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
connect(sock, $0, socklen_t(MemoryLayout.stride))
}
}

which both compile and run correctly.

My questions are:
- Are both solutions correct, should one be preferred, or are both wrong?
- Can the same be achieved simpler?

Thanks,
Martin



___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] Memory layout of enums

2016-08-01 Thread Martin R via swift-users
I think that is treated in 
https://github.com/apple/swift/blob/master/docs/ABI.rst, in the sections 
"Single-Payload Enums" and "Multi-Payload Enums".

Martin

> On 01 Aug 2016, at 08:36, KS Sreeram via swift-users  
> wrote:
> 
> Hi
> 
> Is there any place I can read about the memory layout of enums with 
> associated values? I’m only interested in POD types. Thanks in advance.
> 
> Best
> KS Sreeram
> 
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] Can't initialise using a UTF8 string from within 'withUnsafeBufferPointer' expression

2016-07-18 Thread Martin R via swift-users
This is not an answer to your question, but note that you can pass a Swift 
String to functions expecting an UnsafePointer (C String) parameter, and 
the compiler will generate a temporary NUL-terminated UTF-8 representation for 
you:

  let io = DispatchIO(type: .stream, path: "/path/to/file", ...)

So you don't need a convenience initializer for _this_ purpose.

> On 18 Jul 2016, at 07:17, Karl via swift-users  wrote:
> 
> As I understand it, we are supposed to use withUnsafe{Mutable/Buffer}Pointer 
> or withExtendedLifetime to guarantee that objects we take pointers of will 
> exist and won’t be optimised out by the compiler.
> 
> However, this leads to a problem when trying to initialise something which 
> expects a UTF8 string using only the standard library (not Foundation’s 
> equivalent cStringUsingEncoding):
> 
>> extension DispatchIO {
>> 
>>  convenience init(type: DispatchIO.StreamType, path: String, oflag: 
>> Int32, mode: mode_t, queue: DispatchQueue, cleanupHandler: (error: Int32) -> 
>> Void) {
>> 
>>  let utf8Path = path.nulTerminatedUTF8
>>  utf8Path.withUnsafeBufferPointer {
>>  self.init(type: type, path: 
>> UnsafePointer($0.baseAddress!), oflag: oflag, mode: mode, queue: queue, 
>> cleanupHandler: cleanupHandler)
>>  }
>>  }
>> }
> 
> ERROR: Initializer delegation ('self.init') cannot be nested in another 
> expression
> 
> I don’t really understand why that isn’t allowed for a non-capturing closure, 
> but if we accept that, how do I actually use those pointer/extended lifetime 
> functions to initialise things?
> 
> Thanks
> 
> Karl
> 
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] Redeclaration of guard variable is ignored at top-level

2016-06-17 Thread Martin R via swift-users
Filed as https://bugs.swift.org/browse/SR-1804.

2016-06-17 7:17 GMT-07:00 Mark Lacey <mark.la...@apple.com>:
>
> On Jun 16, 2016, at 10:18 PM, Martin R via swift-users
> <swift-users@swift.org> wrote:
>
> Hi,
>
> I wonder why the Swift compiler does not complain about the
> redeclaration of `number` after the guard-statement in top-level code:
>
>// main.swift
>import Swift
>
>guard let number = Int("1234") else { fatalError() }
>print(number) // Output: 1234
>let number = 5678
>print(number) // Output: 1234
>
> It looks as if the statement `let number = 5678` is completely ignored.
>
> However, doing the same inside a function causes a compiler error:
>
>func foo() {
>guard let number = Int("1234") else { fatalError() }
>print(number)
>let number = 5678 //  error: definition conflicts with previous value
>}
>
> Tested with
> - Xcode 7.3.1, "Default" and "Snapshot 2016-06-06 (a)" toolchain
> - Xcode 8 beta.
>
> Am I overlooking something or is that a bug?
>
>
> Hi Martin,
>
> Yes, this looks like a bug. Can you open a report at bugs.swift.org?
>
> Mark
>
>
> Martin
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users
>
>
___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


[swift-users] Redeclaration of guard variable is ignored at top-level

2016-06-16 Thread Martin R via swift-users
Hi,

I wonder why the Swift compiler does not complain about the
redeclaration of `number` after the guard-statement in top-level code:

// main.swift
import Swift

guard let number = Int("1234") else { fatalError() }
print(number) // Output: 1234
let number = 5678
print(number) // Output: 1234

It looks as if the statement `let number = 5678` is completely ignored.

However, doing the same inside a function causes a compiler error:

func foo() {
guard let number = Int("1234") else { fatalError() }
print(number)
let number = 5678 //  error: definition conflicts with previous value
}

Tested with
- Xcode 7.3.1, "Default" and "Snapshot 2016-06-06 (a)" toolchain
- Xcode 8 beta.

Am I overlooking something or is that a bug?

Martin
___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users