Re: [swift-users] Cannot pass immutable value as inout argument

2018-01-17 Thread Geordie Jay via swift-users
Jordan Rose via swift-users  schrieb am Mi. 17. Jan.
2018 um 01:38:

> Oh no, you're right, I'm sorry. You can only do that with arrays at the
> moment. We do have a bug for this already.
>
> Jordan
>

But couldn’t you call it like this:

lgs_notify_params_t(notify: [lgs_notify_did_enter_background])


For exactly that reason?

- Geordie


>
> On Jan 16, 2018, at 16:37, Roderick Mann  wrote:
>
> Xcode can't properly parse the C header to show me the Swift signature,
> but if I try calling it like this:
>
>let p = lgs_notify_params_t(notify: lgs_notify_did_enter_background)
>lgs_notify(self.ctx, p)
>
> I get this error:
>
> Cannot convert value of type 'lgs_notify_params_t' to expected argument
> type 'UnsafePointer!'
>
>
> On Jan 16, 2018, at 13:22 , Jordan Rose  wrote:
>
> You can do this if you don't write '&', which incorporates the caveat that
> you're not passing a stable address. But please file a bug anyway, because
> the diagnostic should tell you that!
>
> Jordan
>
>
> On Jan 16, 2018, at 13:10, Rick Mann via swift-users <
> swift-users@swift.org> wrote:
>
> Is it not possible for Swift to treat C API const pointers as something
> that can take let arguments?
>
>
> LGS_EXPORT bool lgs_notify(struct lgs_context_t* ctx, const
> lgs_notify_params_t* params);
> .
> .
> .
> let p = lgs_notify_params_t(...)
> lgs_notify(self.ctx, &p)
>^Cannot pass immutable value as inout argument: 'p' is
> a 'let' constant
>
>
> Why isn't the "const" in the C declaration enough to let Swift know it's
> const and just allow it to be a let?
>
> --
> Rick Mann
> rm...@latencyzero.com
>
>
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users
>
>
>
>
> --
> Rick Mann
> rm...@latencyzero.com
>
>
> ___
> 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] A problem about interact with C macros

2017-12-17 Thread Geordie Jay via swift-users
Thinking about this a bit more:

Imagine you imported another header later that “#undef SITUATION2” and then
redefined it with a different value. The fact that SITUATIONALL is an
expression and not a value would then produce a different result. For some
this would be expected and for others a debugging nightmare. Since there is
no “right” answer, I’d say macro expressions like this will never be
imported by Swift.

- Geordie
Geordie Jay via swift-users  schrieb am So. 17. Dez.
2017 um 14:40:

> I think this is because the C preprocessor will interpret SITUATIONALL not
> as a value but as an expression. That means your C code at that spot will
> be turned into “(SITUATION1 | SITUATION2 | etc)” and not into the result of
> that expression directly.
>
> The clang importer could probably figure this out, but I suspect there are
> diminishing returns in figuring out what really is a constant as opposed to
> another expression etc. Especially in this example, the inconvenience of
> defining your own SITUATIONALL in Swift is likely lower than the
> inconvenience of that where the macro expression imports incorrectly and
> does unexpected things.
>
> Please (anyone) correct me if I’m wrong here though, I’d like to know the
> definitive answer myself.
>
> - Geordie
>
> Li Keqing via swift-users  schrieb am So. 17. Dez.
> 2017 um 13:08:
>
>> Here are some macros in C headers such as
>>
>> #define SITUATION1 0x0001
>> #define SITUATION1 0x0002
>> #define SITUATION3 0x0004
>> #define SITUATION4 0x0008
>> #define SITUATIONALL (SITUATION1 | SITUATION2 | SITUATION3 | SITUATION4)
>>
>> when use these value in swift
>> those lines are okay
>> let value1 = SITUATION1
>> let value2 = SITUATION2
>> let value3 = SITUATION3
>> let value4 = SITUATION4
>> but this line would show error
>> let valueAll = SITUATIONALL
>>
>>  Is it a bug ? or just be designed as it?
>> ___
>> 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] A problem about interact with C macros

2017-12-17 Thread Geordie Jay via swift-users
I think this is because the C preprocessor will interpret SITUATIONALL not
as a value but as an expression. That means your C code at that spot will
be turned into “(SITUATION1 | SITUATION2 | etc)” and not into the result of
that expression directly.

The clang importer could probably figure this out, but I suspect there are
diminishing returns in figuring out what really is a constant as opposed to
another expression etc. Especially in this example, the inconvenience of
defining your own SITUATIONALL in Swift is likely lower than the
inconvenience of that where the macro expression imports incorrectly and
does unexpected things.

Please (anyone) correct me if I’m wrong here though, I’d like to know the
definitive answer myself.

- Geordie

Li Keqing via swift-users  schrieb am So. 17. Dez.
2017 um 13:08:

> Here are some macros in C headers such as
>
> #define SITUATION1 0x0001
> #define SITUATION1 0x0002
> #define SITUATION3 0x0004
> #define SITUATION4 0x0008
> #define SITUATIONALL (SITUATION1 | SITUATION2 | SITUATION3 | SITUATION4)
>
> when use these value in swift
> those lines are okay
> let value1 = SITUATION1
> let value2 = SITUATION2
> let value3 = SITUATION3
> let value4 = SITUATION4
> but this line would show error
> let valueAll = SITUATIONALL
>
>  Is it a bug ? or just be designed as it?
> ___
> 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 Geordie Jay via swift-users
Jens Alfke  schrieb am Mi. 8. Nov. 2017 um 16:54:

>
>
> On Nov 8, 2017, at 2:24 AM, Geordie Jay via swift-users <
> swift-users@swift.org> wrote:
>
> Would you be able to clarify where the line is between “tricky” and “not
> tricky” and if possible the reasoning behind making this distinction?
> Because as an outsider this seems to me like an unfortunate remnant of ObjC
> rather than an obvious and forward-thinking API decision.
>
>
> The “only available after importing Foundation” thing has been around
> since 1.0 — it’s an artifact of the bridging of String and NSString*. After
> importing Foundation, the methods of NSString are implicitly available as
> an extension of String. I would think that by now the Swift standard
> library would have added those methods, but I guess not all of them…
>

Hi, and thanks for your response.

I’m aware of the legacy. What I meant was I’m surprised that
String.contains(anotherString) returns two different things depending
whether or not Foundation is imported.

And I was looking for some clarification re: “tricky” vs not. I gather
NSString didn’t even exist in ObjC outside of Foundation. What I was
getting at was whether it makes sense to stick with the status quo on this
point.

Geordie


> —Jens
>
> * And IIRC it also manifests with Array, Dictionary, and other bridged
> classes.
>
___
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 Geordie Jay via swift-users
Quinn "The Eskimo!" via swift-users  schrieb am Mi.
8. Nov. 2017 um 09:56:

>
> On 8 Nov 2017, at 08:47, Martin R via swift-users 
> wrote:
>
> > but apparently only if Foundation is imported.
>
> Which isn’t a huge surprise when you consider how tricky string
> containment is.


As someone who has used Swift professionally since it first came out, this
subtle API change after import actually is a surprise to me.

Would you be able to clarify where the line is between “tricky” and “not
tricky” and if possible the reasoning behind making this distinction?
Because as an outsider this seems to me like an unfortunate remnant of ObjC
rather than an obvious and forward-thinking API decision.


>
> 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!")
> }


In Swiss German “Straße” and “Strasse” are equivalent (or rather, the first
one doesn’t officially exist). In High/“Standard” German they’re not /
would be pronounced differently etc. Some Germans call the “sharp s” an
“sz” instead. So the difficulty of this distinction is not restricted to
Unicode :)

Cheers,
Geordie


>
> 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] dealing with heterogenous lists/dictionary with Codable

2017-10-19 Thread Geordie Jay via swift-users
David Baraff  schrieb am Do. 19. Okt. 2017 um 21:35:

>
>
> Begin forwarded message:
>
> From: Geordie Jay 
>
> Subject: Re: [swift-users] dealing with heterogenous lists/dictionary with
> Codable
>
> Date: October 19, 2017 at 12:24:44 PM PDT
>
> To: David Baraff , Itai Ferber 
>
> Cc: swift-users 
>
>
>
>
> David Baraff  schrieb am Do. 19. Okt. 2017 um
> 21:14:
>
>> My apologies.  I misstated the problem: I don’t want to just limit to
>> Int, String, [Int], etc. but also allow structures where
>>
>> struct NewThingy : Codable {
>> let data1: T1
>> let data2: T2
>> }
>>
>> where T1 and T2 are themselves Codable.
>>
>
> This is already possible, just not with dictionaries of unknown types
> (because they’re not known to be Codable)
>
>
> Sure, but I don’t want to give a dictionary of unknown types: i’m very
> happy to say that my dictionary is
> [String : Codable]
>
> but
> struct Foo : Codable {
> let d: [String : Codable]
> }
>
> doesn’t work; the d inside F is not itself Codable.
>

That’s strange. We’re actually doing exactly this and it works for us
(although we are using a concrete Codable type rather than the Codable
metatype itself).

Maybe it’s worth filing a bug on Jira

Good luck.


>
>
>> So basically, back to wanting to let the compiler do the work, when I
>> make new structures, while still allowing for heterogenous containers.
>>
>
> It’s also possible to give the compiler hints as to what decodes into
> what. Have you looked at the docs on the Apple foundation page?
>
>
> https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types
>
> Geordie
>
>
>
>
>>
>>
>>
>>
>> Begin forwarded message:
>>
>> From: Itai Ferber 
>>
>> Subject: Re: [swift-users] dealing with heterogenous lists/dictionary
>> with Codable
>>
>> Date: October 19, 2017 at 10:40:28 AM PDT
>>
>> To: David Baraff 
>>
>> Cc: Geordie Jay , swift-users 
>>
>>
>> Why are you stuck? I think the following matches your needs, no?
>>
>> import Foundation
>> enum MyType : Codable, Equatable {
>> case int(Int)
>> case string(String)
>> case list([MyType])
>> case dictionary([String : MyType])
>>
>> public init(from decoder: Decoder) throws {
>> // Can be made prettier, but as a simple example:
>> let container = try decoder.singleValueContainer()
>> do {
>> self = .int(try container.decode(Int.self))
>> } catch DecodingError.typeMismatch {
>> do {
>> self = .string(try container.decode(String.self))
>> } catch DecodingError.typeMismatch {
>> do {
>> self = .list(try container.decode([MyType].self))
>> } catch DecodingError.typeMismatch {
>> self = .dictionary(try container.decode([String : 
>> MyType].self))
>> }
>> }
>> }
>> }
>>
>> public func encode(to encoder: Encoder) throws {
>> var container = encoder.singleValueContainer()
>> switch self {
>> case .int(let int): try container.encode(int)
>> case .string(let string): try container.encode(string)
>> case .list(let list): try container.encode(list)
>> case .dictionary(let dictionary): try container.encode(dictionary)
>> }
>> }
>>
>> static func ==(_ lhs: MyType, _ rhs: MyType) -> Bool {
>> switch (lhs, rhs) {
>> case (.int(let int1), .int(let int2)): return int1 == int2
>> case (.string(let string1), .string(let string2)): return string1 == 
>> string2
>> case (.list(let list1), .list(let list2)): return list1 == list2
>> case (.dictionary(let dict1), .dictionary(let dict2)): return dict1 
>> == dict2
>> default: return false
>> }
>> }
>> }
>> let values: MyType = .list([.int(42), .string("hello!"), .list([.int(9), 
>> .string("hi")]), .dictionary(["zero": .int(0), "one": 
>> .int(1)])])print(values)
>> let encoder = JSONEncoder()let data = try 
>> encoder.encode(values)print(String(data: data, encoding: .utf8)!) // => 
>> [42,"hello!",[9,"hi"],{"zero":0,"one":1}]
>> let decoder = JSONDecoder()let decoded = try decoder.decode(MyType.self, 
>> from: data)print(decoded)
>> print(values == decoded) // => true
>>
>> On 19 Oct 2017, at 20:15, David Baraff wrote:
>>
>> Begin forwarded message:
>>
>> From: Itai Ferber 
>>
>> Subject: Re: [swift-users] dealing with heterogenous lists/dictionary
>> with Codable
>>
>> Date: October 19, 2017 at 9:39:25 AM PDT
>>
>> To: David Baraff 
>>
>> Cc: Geordie Jay , swift-users 
>>
>>
>> Hi David and Geordie,
>>
>> That approach won’t work — encoders and decoders only work directly with
>> concrete Codable types (e.g. String, Int, MyFoo [where MyFoo is Codable],
>> etc.).
>> This is by design: since there is no type information stored in the JSON
>> payload, there isn’t necessarily a way to tell how to decode the type
>> you’re looking at, so asking for a generalCo

Re: [swift-users] dealing with heterogenous lists/dictionary with Codable

2017-10-19 Thread Geordie Jay via swift-users
David Baraff  schrieb am Do. 19. Okt. 2017 um 21:14:

> My apologies.  I misstated the problem: I don’t want to just limit to Int,
> String, [Int], etc. but also allow structures where
>
> struct NewThingy : Codable {
> let data1: T1
> let data2: T2
> }
>
> where T1 and T2 are themselves Codable.
>

This is already possible, just not with dictionaries of unknown types
(because they’re not known to be Codable)


> So basically, back to wanting to let the compiler do the work, when I make
> new structures, while still allowing for heterogenous containers.
>

It’s also possible to give the compiler hints as to what decodes into what.
Have you looked at the docs on the Apple foundation page?

https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types

Geordie




>
>
>
>
> Begin forwarded message:
>
> From: Itai Ferber 
>
> Subject: Re: [swift-users] dealing with heterogenous lists/dictionary with
> Codable
>
> Date: October 19, 2017 at 10:40:28 AM PDT
>
> To: David Baraff 
>
> Cc: Geordie Jay , swift-users 
>
>
> Why are you stuck? I think the following matches your needs, no?
>
> import Foundation
> enum MyType : Codable, Equatable {
> case int(Int)
> case string(String)
> case list([MyType])
> case dictionary([String : MyType])
>
> public init(from decoder: Decoder) throws {
> // Can be made prettier, but as a simple example:
> let container = try decoder.singleValueContainer()
> do {
> self = .int(try container.decode(Int.self))
> } catch DecodingError.typeMismatch {
> do {
> self = .string(try container.decode(String.self))
> } catch DecodingError.typeMismatch {
> do {
> self = .list(try container.decode([MyType].self))
> } catch DecodingError.typeMismatch {
> self = .dictionary(try container.decode([String : 
> MyType].self))
> }
> }
> }
> }
>
> public func encode(to encoder: Encoder) throws {
> var container = encoder.singleValueContainer()
> switch self {
> case .int(let int): try container.encode(int)
> case .string(let string): try container.encode(string)
> case .list(let list): try container.encode(list)
> case .dictionary(let dictionary): try container.encode(dictionary)
> }
> }
>
> static func ==(_ lhs: MyType, _ rhs: MyType) -> Bool {
> switch (lhs, rhs) {
> case (.int(let int1), .int(let int2)): return int1 == int2
> case (.string(let string1), .string(let string2)): return string1 == 
> string2
> case (.list(let list1), .list(let list2)): return list1 == list2
> case (.dictionary(let dict1), .dictionary(let dict2)): return dict1 
> == dict2
> default: return false
> }
> }
> }
> let values: MyType = .list([.int(42), .string("hello!"), .list([.int(9), 
> .string("hi")]), .dictionary(["zero": .int(0), "one": .int(1)])])print(values)
> let encoder = JSONEncoder()let data = try 
> encoder.encode(values)print(String(data: data, encoding: .utf8)!) // => 
> [42,"hello!",[9,"hi"],{"zero":0,"one":1}]
> let decoder = JSONDecoder()let decoded = try decoder.decode(MyType.self, 
> from: data)print(decoded)
> print(values == decoded) // => true
>
> On 19 Oct 2017, at 20:15, David Baraff wrote:
>
> Begin forwarded message:
>
> From: Itai Ferber 
>
> Subject: Re: [swift-users] dealing with heterogenous lists/dictionary with
> Codable
>
> Date: October 19, 2017 at 9:39:25 AM PDT
>
> To: David Baraff 
>
> Cc: Geordie Jay , swift-users 
>
>
> Hi David and Geordie,
>
> That approach won’t work — encoders and decoders only work directly with
> concrete Codable types (e.g. String, Int, MyFoo [where MyFoo is Codable],
> etc.).
> This is by design: since there is no type information stored in the JSON
> payload, there isn’t necessarily a way to tell how to decode the type
> you’re looking at, so asking for a generalCodable` isn’t helpful.
>
> Since it’s unlikely that what you truly need is a [String : Any] but
> really a [String : ], one easy way to
> decode this type is to create a wrapper enum or similar which overrides
> init(from:) to be able to decode from one of those types. You can then
> ask to decode a [String : MyWrapperType] and use that instead.
>
> What types are you expecting in the dictionary?
>
>
> The problem is that I want to be able to encode types T where
> (a) T is String, Int
> (b) lists of T
> (c ) dictionaries of type 
>
> The problem is the recursive nature: yes, my types are simple (say only
> base types String and Int) but the “nesting” level may be quite deep (a
> list of list of dictionaries of 
>
> Let’s turn this around:  in addition to the JSONEncoder, one can also use
> the PropertyListEncoder.
>
> Are we saying that something one could pull from a property list file
> (which is pretty much wh

Re: [swift-users] dealing with heterogenous lists/dictionary with Codable

2017-10-19 Thread Geordie Jay via swift-users
I mean can you do something along the lines of

let codableDict = stringAnyDict as? [String : Codable]

?

I’m not at a computer to test it myself




David Baraff  schrieb am Do. 19. Okt. 2017 um 15:45:

> That’s exactly what I want.  The ironic part is that I got my dictionary
> by decoding a Json file.  If that’s where my dictionary came from, is there
> a simple way of coercing the Json serialization routines to give me back
> codables, rather than Anys?
>
>
> Sent from my iPad
>
> On Oct 19, 2017, at 3:38 AM, Geordie Jay  wrote:
>
>
> David Baraff via swift-users  schrieb am Do. 19.
> Okt. 2017 um 03:47:
>
>> So I have simple structs like this:
>>
>> struct Library: Codable {
>> let domain: String
>> let unit: String
>> }
>>
>> and it’s super-simple to serialize.  Yay.
>>
>> But:
>>
>> struct LibraryGroup : Codable { // I wish...
>>let libraries: [Library]
>>let someDict: [String : Any]
>> }
>>
>
> I haven’t tried this, but is it possible to have a dictionary of [String :
> Codable] ? Because that’s exactly the type requirements you’re describing,
> no?
>
> Geordie
>
>
>> So what I’m looking for is something where if the values in someDict are
>> themselves Codable, I can serialize things, and if they’re not, I can’t.
>> In my previous scheme, I was using NSKeyedArchiver to serialize everything,
>> manualy, including someDict; in trying to switch to Codable I ran smack
>> into the fact that Codable wants to know what all the types are, in advance.
>>
>> Am I just stuck?  How do I get the best of both worlds, where the
>> compiler can make use of the fact that it can see the data types of my
>> structures, while still being able to serialize heterogenous data like is
>> found in LibraryGroup?
>>
>> Is my only alternative to write a custom coder for LibraryGroup?  Is
>> there any hope I could teach Codable what to do with
>> [String: Any]
>>
>> ?
>>
>>
>> ___
>> 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] dealing with heterogenous lists/dictionary with Codable

2017-10-19 Thread Geordie Jay via swift-users
David Baraff via swift-users  schrieb am Do. 19.
Okt. 2017 um 03:47:

> So I have simple structs like this:
>
> struct Library: Codable {
> let domain: String
> let unit: String
> }
>
> and it’s super-simple to serialize.  Yay.
>
> But:
>
> struct LibraryGroup : Codable { // I wish...
>let libraries: [Library]
>let someDict: [String : Any]
> }
>

I haven’t tried this, but is it possible to have a dictionary of [String :
Codable] ? Because that’s exactly the type requirements you’re describing,
no?

Geordie


> So what I’m looking for is something where if the values in someDict are
> themselves Codable, I can serialize things, and if they’re not, I can’t.
> In my previous scheme, I was using NSKeyedArchiver to serialize everything,
> manualy, including someDict; in trying to switch to Codable I ran smack
> into the fact that Codable wants to know what all the types are, in advance.
>
> Am I just stuck?  How do I get the best of both worlds, where the compiler
> can make use of the fact that it can see the data types of my structures,
> while still being able to serialize heterogenous data like is found in
> LibraryGroup?
>
> Is my only alternative to write a custom coder for LibraryGroup?  Is there
> any hope I could teach Codable what to do with
> [String: Any]
>
> ?
>
>
> ___
> 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 Geordie Jay via swift-users
Chris Lattner  schrieb am Sa. 14. Okt. 2017 um 05:18:

>
> On Oct 13, 2017, at 7:40 PM, Andrew Trick via swift-users <
> swift-users@swift.org> wrote:
>
>
>
> On Oct 12, 2017, at 3:52 AM, Geordie Jay via swift-users <
> swift-users@swift.org> 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?

- Geordie


> -Chris
>
>
>
___
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-12 Thread Geordie Jay via swift-users
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


>
> Guillaume Lessard
>
> ___
> 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] [Feature Request] Extend the `defer` statement

2017-10-09 Thread Geordie Jay via swift-users
This feature request is probably one for swift evolution.

I like the idea in theory, but I’d prefer to see the return value
identifier being spelled out, i.e. “returnValue” instead of the symbols.

Jun Zhang via swift-users  schrieb am Mo. 9. Okt.
2017 um 05:37:

> Yes that's true, but this requires me to set a return value in every
> `early return` statement. I think this should be done by the compiler
> instead of me, to make code cleaner and also less error-prone.
>
> On Mon, Oct 9, 2017 at 11:24 AM, Slava Pestov  wrote:
>
>> I think you can achieve what you want by having the ‘defer’ block capture
>> a mutable local variable. Eg,
>>
>> func doStuff() {
>>   var success = false
>>
>>   defer {
>> if !success {
>>   // do some additional cleanup
>> }
>>   }
>>
>>   …
>>   success = true
>>   …
>>
>>   return result
>> }
>>
>> On Oct 8, 2017, at 7:34 PM, Jun Zhang via swift-users <
>> swift-users@swift.org> wrote:
>>
>> Hi dear swift developers,
>>I am kind of new to swift and I don't know if this feature already
>> exists. And if it exists already please tell me how. Thank you very much!
>>   The feature is to capturing the return value (maybe input value also)
>> of the function. Here is the demo code:
>>
>> func tableView(_ tableView: UITableView, numberOfRowsInSection
>> section: Int) -> Int {
>> defer {
>> if $> >= 0 {
>> // table is not empty
>> }
>> else {
>> // table is empty
>> }
>> }
>> return dataSource.cout
>> }
>>
>>I suggest using `$>` as the return value symbol and `$<` as the input
>> parameter symbol.
>>
>>
Also, I’m not sure what “input parameter” means here.

Geordie


   Thank you all and best regards to you!
>> ___
>> 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] Communicating with dynamically loaded swift library

2017-10-07 Thread Geordie Jay via swift-users
Ján Kosa  schrieb am Sa. 7. Okt. 2017 um 15:27:

> I tried to use @_exported and it helped somewhat. While I still have same
> warnings, size of the PluginInterface library went down by 6mb (to 120kb)
> so it looks like Protobuf is no longer statically linked to it. However,
> size of PluginConsumer executable went up by same 6mb, it looks like it is
> linked there twice now.
>

To be clear: take protobuf out of the PluginConsumer dependencies.
Actually, I’m not sure which is which, but protobuf should only be listed
as a dependency of one package, where it is imported as @_exported. After
that, your other modules depend on the package that imports / exports
protobuf.

I also noticed interesting thing. If I build executable using `swift build`
> the size is around 17mb, when I generate xcode project and build it using
> that, size is around 200kb, but I get same warnings using both approaches
>
> On 7 October 2017 at 15:44, Geordie Jay  wrote:
>
>>
>> Ján Kosa  schrieb am Sa. 7. Okt. 2017 um 13:34:
>>
>>> I tried swift package clean, but it didn't help
>>>
>>> "Try to ensure the plugin provider module (libA) is (only) being
>>> compiled into its standalone shared library file."
>>> How do I go about this? It is 3rd party module, it doesn't define any
>>> products (https://github.com/apple/swift-protobuf.git). Is there
>>> something I can do in my Package files to make sure it is loaded
>>> dynamically?
>>>
>>
>> When you compile a package depending on protobuf, all the relevant
>> symbols end up in your package’s library file. So here’s something you
>> might try:
>>
>> import protobuf into your own “PluginProvider” module (package), which
>> has a shared library product like this: ‘@_exported import Protobuf’ in
>> some compiled swift file. Then from the other dependent modules “import
>> PluginProvider” - the protobuf symbols should be available, and all from
>> one (nonconflicting) source.
>>
>> Geordie
>>
>>
>>
>>> On 6 October 2017 at 22:52, Geordie Jay  wrote:
>>>
 I think SwiftPM is (incorrectly) compiling A.XYZ into each of the
 modules that depend on it, as well as into your intended libA.so file.

 Try to ensure the plugin provider module (libA) is (only) being
 compiled into its standalone shared library file. Try cleaning the swiftpm
 build for one (swift package clean) and ensure the Package.swift files are
 correctly set up to output the shared library.

 Sorry I can’t be more specific, I’ve had these same kinds of issues
 before but I’m not 100% what they were.

 Geordie


 Ján Kosa via swift-users  schrieb am Fr. 6.
 Okt. 2017 um 14:41:

> It worked! Took me a while to iron out details, but it is working now.
> Huge thanks sir, I will name my firstborn after you.
> Thanks for the @_cdecl("initializePlugin") tip as well, I didn't know
> about it and it will be very useful.
>
> I am having slightly related problem now (it was there before, but I
> ignored it for the time being), not sure if I should start a new thread?
>
> The PluginInterface module has one external dependency on module A,
> PluginConsumer has the dependency on module B which has dependency on same
> module A that the PluginInterface uses. When I load the plugin library, I
> get bunch of errors like:
>
> Class A.XYZ is implemented in both libPluginInterface.dylib and
> libMyPlugin.dylib
>
> I know why it is there, but I don't know how to get rid of it. I can't
> just remove dependency from PluginConsumer and use the one from
> PluginInterface (if that would even work?) because PluginConsumer does not
> depend on it directly, but it is going through module B first
>
> Cheers,
> Lope
>
> On 4 October 2017 at 22:17, Daniel Dunbar 
> wrote:
>
>> The way that I have done this in the past is pass a protocol as an
>> unsafe pointer to an exposed entry point:
>> ```swift
>> let entryPoint = dlsym(handle, “initializePlugin”)
>> guard entryPoint != nil else {
>> fatalError("missing plugin entry point:
>> \(pluginPath)")
>> }
>> typealias PluginInitializationFunc = @convention(c)
>> (UnsafeRawPointer) -> ()
>> let f = unsafeBitCast(entryPoint, to:
>> PluginInitializationFunc.self)
>> f(Unmanaged.passUnretained(self).toOpaque())
>> ```
>>
>> and then in the plugin convert back to the appropriate type:
>>
>> ```
>> @_cdecl("initializePlugin")
>> public func initializePlugin(_ ptr: UnsafeRawPointer) {
>> let manager =
>> Unmanaged.fromOpaque(ptr).takeUnretainedValue()
>> ```
>>
>> HTH,
>>  - Daniel
>>
>> On Oct 4, 2017, at 11:02 AM, Ján Kosa via swift-users <
>> swift-users@swift.org> wrote:
>>
>> Hello folks,
>>
>> I have been toying with dynamic

Re: [swift-users] Communicating with dynamically loaded swift library

2017-10-07 Thread Geordie Jay via swift-users
Ján Kosa  schrieb am Sa. 7. Okt. 2017 um 13:34:

> I tried swift package clean, but it didn't help
>
> "Try to ensure the plugin provider module (libA) is (only) being compiled
> into its standalone shared library file."
> How do I go about this? It is 3rd party module, it doesn't define any
> products (https://github.com/apple/swift-protobuf.git). Is there
> something I can do in my Package files to make sure it is loaded
> dynamically?
>

When you compile a package depending on protobuf, all the relevant symbols
end up in your package’s library file. So here’s something you might try:

import protobuf into your own “PluginProvider” module (package), which has
a shared library product like this: ‘@_exported import Protobuf’ in some
compiled swift file. Then from the other dependent modules “import
PluginProvider” - the protobuf symbols should be available, and all from
one (nonconflicting) source.

Geordie



> On 6 October 2017 at 22:52, Geordie Jay  wrote:
>
>> I think SwiftPM is (incorrectly) compiling A.XYZ into each of the
>> modules that depend on it, as well as into your intended libA.so file.
>>
>> Try to ensure the plugin provider module (libA) is (only) being compiled
>> into its standalone shared library file. Try cleaning the swiftpm build for
>> one (swift package clean) and ensure the Package.swift files are correctly
>> set up to output the shared library.
>>
>> Sorry I can’t be more specific, I’ve had these same kinds of issues
>> before but I’m not 100% what they were.
>>
>> Geordie
>>
>>
>> Ján Kosa via swift-users  schrieb am Fr. 6. Okt.
>> 2017 um 14:41:
>>
>>> It worked! Took me a while to iron out details, but it is working now.
>>> Huge thanks sir, I will name my firstborn after you.
>>> Thanks for the @_cdecl("initializePlugin") tip as well, I didn't know
>>> about it and it will be very useful.
>>>
>>> I am having slightly related problem now (it was there before, but I
>>> ignored it for the time being), not sure if I should start a new thread?
>>>
>>> The PluginInterface module has one external dependency on module A,
>>> PluginConsumer has the dependency on module B which has dependency on same
>>> module A that the PluginInterface uses. When I load the plugin library, I
>>> get bunch of errors like:
>>>
>>> Class A.XYZ is implemented in both libPluginInterface.dylib and
>>> libMyPlugin.dylib
>>>
>>> I know why it is there, but I don't know how to get rid of it. I can't
>>> just remove dependency from PluginConsumer and use the one from
>>> PluginInterface (if that would even work?) because PluginConsumer does not
>>> depend on it directly, but it is going through module B first
>>>
>>> Cheers,
>>> Lope
>>>
>>> On 4 October 2017 at 22:17, Daniel Dunbar 
>>> wrote:
>>>
 The way that I have done this in the past is pass a protocol as an
 unsafe pointer to an exposed entry point:
 ```swift
 let entryPoint = dlsym(handle, “initializePlugin”)
 guard entryPoint != nil else {
 fatalError("missing plugin entry point: \(pluginPath)")
 }
 typealias PluginInitializationFunc = @convention(c)
 (UnsafeRawPointer) -> ()
 let f = unsafeBitCast(entryPoint, to:
 PluginInitializationFunc.self)
 f(Unmanaged.passUnretained(self).toOpaque())
 ```

 and then in the plugin convert back to the appropriate type:

 ```
 @_cdecl("initializePlugin")
 public func initializePlugin(_ ptr: UnsafeRawPointer) {
 let manager =
 Unmanaged.fromOpaque(ptr).takeUnretainedValue()
 ```

 HTH,
  - Daniel

 On Oct 4, 2017, at 11:02 AM, Ján Kosa via swift-users <
 swift-users@swift.org> wrote:

 Hello folks,

 I have been toying with dynamic libraries, trying to implement plugin
 functionality. I was able to get to the point where I can call simple
 function in loaded library, but I am having troubles starting more
 sophisticated communication channel.

 There are 3 projects
 - PluginConsumer is an app that loads plugin libraries
 - MyPlugin is a plugin implementation, output is dynamic library that
 PluginConsumer loads
 - PluginInterface is common interface that both MyPlugin and
 PluginConsumer use, so that they know how to communicate

 My first idea was to have PluginInterface be a simple SPM project with
 single file where the bare-bones PluginInterface class would be:


 open class PluginInterface {

 open func sayHi()

 }


 Package.swift file:


 // swift-tools-version:4.0

 import PackageDescription

 let package = Package(

 name: "PluginInterface",

 products: [ .library(name: "PluginInterface", type: .dynamic,
 targets: ["PluginInterface"]) ],

 targets: [ .target(name: "PluginInterface") ]

 )



 UserPlugin

Re: [swift-users] Communicating with dynamically loaded swift library

2017-10-06 Thread Geordie Jay via swift-users
I think SwiftPM is (incorrectly) compiling A.XYZ into each of the modules
that depend on it, as well as into your intended libA.so file.

Try to ensure the plugin provider module (libA) is (only) being compiled
into its standalone shared library file. Try cleaning the swiftpm build for
one (swift package clean) and ensure the Package.swift files are correctly
set up to output the shared library.

Sorry I can’t be more specific, I’ve had these same kinds of issues before
but I’m not 100% what they were.

Geordie


Ján Kosa via swift-users  schrieb am Fr. 6. Okt.
2017 um 14:41:

> It worked! Took me a while to iron out details, but it is working now.
> Huge thanks sir, I will name my firstborn after you.
> Thanks for the @_cdecl("initializePlugin") tip as well, I didn't know
> about it and it will be very useful.
>
> I am having slightly related problem now (it was there before, but I
> ignored it for the time being), not sure if I should start a new thread?
>
> The PluginInterface module has one external dependency on module A,
> PluginConsumer has the dependency on module B which has dependency on same
> module A that the PluginInterface uses. When I load the plugin library, I
> get bunch of errors like:
>
> Class A.XYZ is implemented in both libPluginInterface.dylib and
> libMyPlugin.dylib
>
> I know why it is there, but I don't know how to get rid of it. I can't
> just remove dependency from PluginConsumer and use the one from
> PluginInterface (if that would even work?) because PluginConsumer does not
> depend on it directly, but it is going through module B first
>
> Cheers,
> Lope
>
> On 4 October 2017 at 22:17, Daniel Dunbar  wrote:
>
>> The way that I have done this in the past is pass a protocol as an unsafe
>> pointer to an exposed entry point:
>> ```swift
>> let entryPoint = dlsym(handle, “initializePlugin”)
>> guard entryPoint != nil else {
>> fatalError("missing plugin entry point: \(pluginPath)")
>> }
>> typealias PluginInitializationFunc = @convention(c)
>> (UnsafeRawPointer) -> ()
>> let f = unsafeBitCast(entryPoint, to:
>> PluginInitializationFunc.self)
>> f(Unmanaged.passUnretained(self).toOpaque())
>> ```
>>
>> and then in the plugin convert back to the appropriate type:
>>
>> ```
>> @_cdecl("initializePlugin")
>> public func initializePlugin(_ ptr: UnsafeRawPointer) {
>> let manager =
>> Unmanaged.fromOpaque(ptr).takeUnretainedValue()
>> ```
>>
>> HTH,
>>  - Daniel
>>
>> On Oct 4, 2017, at 11:02 AM, Ján Kosa via swift-users <
>> swift-users@swift.org> wrote:
>>
>> Hello folks,
>>
>> I have been toying with dynamic libraries, trying to implement plugin
>> functionality. I was able to get to the point where I can call simple
>> function in loaded library, but I am having troubles starting more
>> sophisticated communication channel.
>>
>> There are 3 projects
>> - PluginConsumer is an app that loads plugin libraries
>> - MyPlugin is a plugin implementation, output is dynamic library that
>> PluginConsumer loads
>> - PluginInterface is common interface that both MyPlugin and
>> PluginConsumer use, so that they know how to communicate
>>
>> My first idea was to have PluginInterface be a simple SPM project with
>> single file where the bare-bones PluginInterface class would be:
>>
>>
>> open class PluginInterface {
>>
>> open func sayHi()
>>
>> }
>>
>>
>> Package.swift file:
>>
>>
>> // swift-tools-version:4.0
>>
>> import PackageDescription
>>
>> let package = Package(
>>
>> name: "PluginInterface",
>>
>> products: [ .library(name: "PluginInterface", type: .dynamic,
>> targets: ["PluginInterface"]) ],
>>
>> targets: [ .target(name: "PluginInterface") ]
>>
>> )
>>
>>
>>
>> UserPlugin is also very simple project containing only one file:
>>
>>
>> public func getPlugin() -> AnyObject {
>>
>> return MyPlugin()
>>
>> }
>>
>>
>> class MyPlugin: PluginInterface {
>>
>> override func sayHi() {
>>
>> print("Hi from my plugin")
>>
>> }
>>
>> }
>>
>> Package.swift:
>>
>>
>> // swift-tools-version:4.0
>>
>> import PackageDescription
>>
>> let package = Package(
>>
>> name: "MyPlugin",
>>
>> products: [ .library(name: "MyPlugin", type: .dynamic, targets: [
>> "MyPlugin"]) ],
>>
>> dependencies: [ .package(url: "url_to_PluginInterface", from: "0.0.0"),
>> ],
>>
>> targets: [
>>
>> .target(name: "PluginInterface", dependencies: ["PluginInterface"
>> ]),
>>
>> .target(name: "MyPlugin", dependencies: ["PluginInterface"]),
>>
>> ]
>>
>> )
>>
>>
>> The PluginConsumer is bit more complicated, but here is relevant part
>> (lib loading and function calling):
>>
>>
>> typealias InitFunction = @convention(c) () -> AnyObject
>>
>>
>> let openRes = dlopen(pathToLib, RTLD_NOW|RTLD_LOCAL)
>>
>> if openRes != nil {
>>
>> defer {
>>
>> dlclose(openRes)
>>
>> }
>>
>> let symbolName = "mangled_symbol_name"
>>
>> let sym = dlsym(openRes, s

Re: [swift-users] Is URLSession actually working on Linux

2017-10-03 Thread Geordie Jay via swift-users
2017-10-03 20:10 GMT+02:00 Georgios Moschovitis via swift-users <
swift-users@swift.org>:

> I implemented a simple RSS feed aggregator. I used code like...
>
> let data = try! Data(contentsOf: feedURL)
>
> or
>
> let session = URLSession(configuration: URLSessionConfiguration.default)
> let task = session.dataTask(with: url, completionHandler:
> completionHandler)
> task.resume()
>
> ...to fetch the data.
>
> While my application worked perfectly when running on macOS, when I tried
> to run
> it on Ubuntu it started crashing *randomly* with errors like...
>
> *** Error in `bin/….': double free or corruption (fasttop):
> 0x7f388ff0 ***
> Aborted
>
> or
>
> Illegal instruction
>
> etc.
>


I haven't seen it myself but I've heard from colleagues that we ran into
the same issues on Android. Foundation depends on libcurl (on Linux at
least?), so we're just going to make our own basic libcurl wrapper that
looks and acts like URLSession until the Foundation one works.


>
> When I switched to KituraRequest (in place of URLSession), the application
> started
> running correctly on Ubuntu as well.
>

KituraRequest uses libcurl too, but its dependency tree is too complex for
us to use on Android.


>
> Are there any issues with the implementation of Foundation for Linux?
>

tldr; Pretty sure, yes.


>
>
> -g.
>
>
> PS: I am using swift 4.0
>
>
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users
>
>
-g
___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] Problem with Access Control and Extensions

2017-09-21 Thread Geordie Jay via swift-users
Adrian Zubarev via swift-users  schrieb am Mi. 20.
Sep. 2017 um 22:13:

> I don’t get your problem here. If you don’t want to debate the correctness
> of your code, why are you asking for help or even showing error messages
> for a code snippet that cannot work?
>
> 1. Drop the access modifier from the extension itself, because this is
> only for convenience, which may or may not rule over the members of the
> extension members. If you’re already explicitly setting the access modifier
> on the extension members then the convenience access modifier makes no
> sense.
> 2. The code cannot work, because you cannot override `viewDidLoad` on a
> class that you don’t own, on a subclass of `UISplitViewController` that
> would be possible.
>

I think the point is that this is possible in ObjcC. So the question is
really whether you can override methods in Swift from classes that are not
your own.

The answer, as far as I’ve seen, is no. Whenever I’ve needed this feature
I’ve used ObjC.

- Geordie



> ```
> class MySplitViewController : UISplitViewController {}
>
> extension MySplitViewController {
> override open func viewDidLoad() {
> super.viewDidLoad()
> /* ... */
> }
> }
> ```
>
>
> Am 20. September 2017 um 21:41:31, Rick Aurbach via swift-users (
> swift-users@swift.org) schrieb:
>
> I am trying to write an extension to a UIKit class, but am running into a
> can’t-win situation:
>
> The code I ‘want’ to write looks like:
>
>
> public extension UISplitViewController {
> override public func viewDidLoad() {
> super.viewDidLoad()
> if UIDevice.current.userInterfaceIdiom == .pad {
> preferredDisplayMode = .automatic
> } else {
> preferredDisplayMode = .primaryOverlay
> }
> }
> }
>
> This generates the error message
>
> /Users/rlaurb/Projects/Cooks-Memory/Cooks-Memory/AppDelegate.swift:131:23:
> Overriding instance method must be as accessible as the declaration it
> overrides
> /Users/rlaurb/Projects/Cooks-Memory/Cooks-Memory/AppDelegate.swift:131:23:
> Overridden declaration is here (UIKit.UIViewController)
>
> But I can’t change the access control of the function to ‘open’, because I
> get the warning that the function can’t be “more” accessible than the
> extension.
>
> And I can’t change the extension’s access to ‘open’ because apparently
> extensions can’t be open.
>
> Now I don’t want to get into a debate about whether this code works — it’s
> just an experiment — but is it even possible to express this idea?? I.e.,
> is it possible to express this idea without subclassing?
>
> Cheers,
>
> Rick Aurbach
>
> ___
> 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] Swift 4 "Cannot use mutating member on immutable value: 'self' is immutable"

2017-09-18 Thread Geordie Jay via swift-users
It seems to me that some of these concerns could be fixed by returning
ArraySlice instead of Array on popFirst(). Then you’d have similar
performance expectations and explicit copying like with String / Substring.

Geordie


Elia Cereda via swift-users  schrieb am Mo. 18. Sep.
2017 um 11:12:

> NSMutableArray does provide O(1) insertion and removal from the start and
> the end of the array (
> http://ciechanowski.me/blog/2014/03/05/exposing-nsmutablearray/).
>
> I think the reason Swift doesn't use this design is because it stores the
> data in a contiguous block of memory.
>
> Elia Cereda
>
> Il giorno 18 set 2017, alle ore 04:48, Jon Shier via swift-users <
> swift-users@swift.org> ha scritto:
>
> Yes, it seems to fly in the face of protocols as they exist in Swift at
> the moment. Given the inability of protocols to guarantee performance
> characteristics, breaking conformant types like this seems like a bad way
> to try and fulfill a separate axis of concern. Wouldn’t a better idea be to
> move things like popFirst(), and other methods requiring O(1) performance,
> to a separate protocol? I’m also pretty sure it’s possible to implement
> popFirst in O(1) for an Array, but Swift’s Array isn't generally very fast,
> at least compared to C / C++.
>
>
>
> Jon
>
> On Sep 17, 2017, at 9:45 PM, Rick Mann via swift-users <
> swift-users@swift.org> wrote:
>
>
> On Sep 17, 2017, at 03:25 , Quinn The Eskimo! via swift-users <
> swift-users@swift.org> wrote:
>
>
> On 15 Sep 2017, at 21:35, Vladimir.S via swift-users <
> swift-users@swift.org> wrote:
>
> … for me it is very strange decision to disallow a method because it is
> 'expensive'.
>
>
> That’s pretty normal for Swift standard library protocols, which define
> not just the behaviour of the routine but expected performance.
>  `popFirst()` is expected to be O(1) and that’s not possible with `Array`.
>
> The rationale behind this decision is, I believe, related to generic
> algorithms.  If I write generic code that uses `popFirst()`, I can only
> guarantee the complexity of my code if I can rely on `popFirst()` being
> O(1).  If someone implements `popFirst()` as O(n), my generic algorithm
> might go from O(n^2) to O(n^3), which is quite a change.
>
> On 16 Sep 2017, at 01:44, Rick Mann via swift-users 
> wrote:
>
> Is the compiler looking at the name "pop" and adding additional
> constraints (and then spewing a bogus error message)?
>
>
> I’m not sure what’s going on here mechanically but, yes, the error message
> is bogus.  This is exactly what SR-5515 is talking about.
>
> If I were in your shoes I’d call this method something other than
> `popFirst()`.  This falls under my standard “if you change the semantics,
> change the name” rule.  Your implementation of `popFirst()` doesn’t conform
> to the semantics of `popFirst()` — it’s O(n) because `removeFirst()` is
> O(n) — and thus you want to avoid calling it `popFirst()`.
>
>
> All right, I'm happy to change the name to "safeRemoveFirst()", but I'm a
> bit irritated that there's an implicit performance constraint based on the
> name alone, without any obvious decorator syntax.
>
>
> --
> Rick Mann
> rm...@latencyzero.com
>
>
> ___
> 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] [swift-evolution] How does "Sequence.joined" work?

2017-08-08 Thread Geordie Jay via swift-users
Daryle Walker via swift-evolution  schrieb am
Di. 8. Aug. 2017 um 21:25:

> On Aug 8, 2017, at 12:35 AM, Félix Cloutier 
> wrote:
>
> All this means is that `joined()` does not create an array that contains
> the new result. It's only as magic as the COW semantics on arrays.
>
>
> So you’re saying the COW semantics for Array and other standard library
> types have secret references/pointers that work even for “let”-mode
> objects, and the Sequence variants the various forms of “joined” need use a
> Sequence/Collection of those secret references?
>

I know nothing about this specific type under the hood and your question
stumped me when I first saw it as well, so take this with a grain of salt:

I think it's basically just storing the arrays internally (as let) and when
you iterate through the collection it just goes through the subsequences
one by one, when the last index of the first is reached it begins with the
next subsequence.

As for how it avoids creating new storage, simple. As someone else
mentioned, this is no more magic than Copy On Write for normal arrays.

let a = [1,2,3]
let b = a // this doesn't produce a copy of the underlying buffer.. I.e.
value semantics but only one buffer needed

^^^ This is the take-home message. And your intuition about COW is correct:
its internal storage is a reference type containing a buffer pointer. When
(and only when) a mutation occurs, the buffer is copied and the new storage
becomes the backing for the resulting struct. Any existing copies remain
unchanged (and truly immutable) because they keep their original storage.

https://github.com/apple/swift/blob/master/stdlib/public/core/ContiguousArrayBuffer.swift


So with that understanding of COW, it becomes easy to imagine all sorts of
containers that don't require additional storage for their contents:

struct JoinedSequenceOfThreeArrays {
  let array1: [T]
  let array2: [T]
  let array3: [T]
}

// still only one array buffer storage is required for all of this:
let c = JoinedSequenceOfThreeArrays(array1: a, array2: a, array3: b)

Does that make sense?

Geordie


> Le 7 août 2017 à 21:12, Daryle Walker via swift-evolution <
> swift-evolut...@swift.org> a écrit :
>
> I was looking at random items at SwiftDoc.org , and
> noticed the “FlattenBidirectionalCollection” structure. It helps implement
> some versions of “joined” from Sequence (probably when the Sequence is also
> a BidirectionalCollection). The directions for the type state that “joined”
> does not create new storage. Then wouldn’t it have to refer to the source
> objects by reference? How; especially how does it work without requiring a
> “&” with “inout” or how it works with “let”-mode objects? Or am I
> misunderstanding how it works behind the covers?
>
> (If there is a secret sauce to have one object refer to another without
> “&”/“inout”/“UnsafeWhateverPointer”, I like to know. It may help with
> implementing an idea. The idea involves extending the language, so
> “compiler magic” that the user can’t access is OK; I’d just claim to use
> the same sauce in my proposal.)
>
>
> —
> Daryle Walker
> Mac, Internet, and Video Game Junkie
> darylew AT mac DOT com
>
> ___
> swift-evolution mailing list
> swift-evolut...@swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
>
___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] SwiftPM manual dependency management

2017-07-22 Thread Geordie Jay via swift-users
Hi Ankit, thanks for your explanations.

Ankit Aggarwal  schrieb am Sa. 22. Juli 2017 um
13:44:

> On 22-Jul-2017, at 3:37 PM, Geordie Jay  wrote:
>
>
> Geordie J  schrieb am Fr. 21. Juli 2017 um 14:39:
>
>> Hi Ankit, thanks for your reply.
>>
>> Am 21.07.2017 um 07:33 schrieb Ankit Aggarwal via swift-users <
>> swift-users@swift.org>:
>>
>>
>>
>> On Thu, Jul 20, 2017 at 10:34 PM, Geordie J via swift-users <
>> swift-users@swift.org> wrote:
>>
>>> Hi all,
>>>
>>> My team and I are trying to use SwiftPM to develop a relatively complex
>>> app with multiple dependencies, all of which are being developed locally
>>> and in parallel. The reason for this is compatibility with an existing
>>> module/import structure used by our iOS app. Maybe I’m doing something very
>>> wrong but my experience so far (2 months in) is that this is extremely
>>> difficult with SwiftPM.
>>>
>>> What I’d love to be able to do is to just run `git add submodule
>>> http://blah.com/mysubmodule.git` in the Packages subdirectory and
>>> SwiftPM would just let me manage dependencies from there myself.
>>>
>>> I was excited to see that SwiftPM 4 has a "Top of Tree" development
>>> option for this purpose. So far my experience with this has not been good.
>>> Firstly because SwiftPM *still* unnecessarily tries to clone my repos
>>> itself (some of which are huge), and secondly because this creates an
>>> absolute path dependency in `.build/dependencies-state.json`, meaning this
>>> setup isn’t sharable within our dev team.
>>>
>>> Attempting this with "local" git urls adds an almost absurd level of
>>> complexity, having to tag each commit for SwiftPM to build. The fact that
>>> we'd need to make a commit to test whether the project even builds is
>>> insane enough as is, let alone the tagging and trying to tell the base
>>> project to use a newer minor version etc etc.
>>>
>>> Adding multiple subtargets is also not an option because the
>>> dependencies (as dynamic libraries) really are shared between multiple
>>> targets/sub-dependencies, which SwiftPM seems to deal with quite well.
>>>
>>> *tldr;* *Please* let us manage dependencies ourselves. It’d be so easy
>>> if Package.swift had an option along the lines of *.Package.local(named:
>>> "XYZ")* that it then looked for in ./Packages/XYZ. Again, maybe I’m
>>> overlooking something but this seems like an obvious and vital option to
>>> have. It’d also simplify the introductory SwiftPM docs significantly.
>>>
>>> Is anyone else having this issue? Would this change really be as simple
>>> and painless as it sounds? I would be prepared to make a pull request along
>>> these lines.
>>>
>>
>> I think you're not really using the Top of Tree feature. You need to add
>> each dependency using its canonical URL, hosted at some server like github.
>> After adding the dependencies, you can use edit feature to put a dependency
>> in Top of Tree mode. To do so, run:
>>
>> $ swift package edit  --path
>> ../path/to/self/managed/checkout/of/the/package
>>
>>
>> Yes, this is what I tried this week. I’m pretty sure this is not a case
>> of misunderstanding the feature or the docs.
>>
>>
>> The package manager will then stop using the cloned repository and use
>> the checkout present at that path (regardless of the state it is in).
>>
>>
>> Yes, but then I have – per dependency – two checkouts of a potentially
>> huge repository. Why force everyone on the dev team to clone a huge repo
>> twice, only to *never* use one of the clones. Also, SwiftPM breaks when
>> —path points at Packages/PackageName, which is exactly where I’d expect the
>> package to be, not in some arbitrary external path (+ some kind of internal
>> checkout cache that will never be used) as well.
>>
>> I haven’t tried to test this recently because it’s a slow process but I
>> have the impression the deps could be even be cloned more than twice,
>> depending on how cleverly SwiftPM realises that multiple Packages have the
>> same dependency.
>>
>> Also, this makes managing interdependent state of development amongst
>> dependencies more difficult than needed. How do we guarantee that devs are
>> on the same commit when using top of tree development? Tagging and managing
>> version numbers etc for day-to-day development is emphatically not an
>> option for us. Since SwiftPM packages only work from a git context anyway,
>> why not allow use of git’s established pattern of dealing with this, namely
>> submodules?
>>
>> Sharing this setup is not automatic, but simple. Each user just needs to
>> run the above command once per dependency.
>>
>>
>> We have about 10 dependencies, *all *of which will* always* be in this
>> state. This seems like a lot of overhead and room for user error, plus it’s
>> a huge workaround for something that could be very simple.
>>
>> Also, you only need to do this if you're actively working on a dependency.
>>
>>
>> The point is that we will *always* be working on the dependencies. This
>> is the core of what we’re do

Re: [swift-users] SwiftPM manual dependency management

2017-07-22 Thread Geordie Jay via swift-users
Geordie J  schrieb am Fr. 21. Juli 2017 um 14:39:

> Hi Ankit, thanks for your reply.
>
> Am 21.07.2017 um 07:33 schrieb Ankit Aggarwal via swift-users <
> swift-users@swift.org>:
>
>
>
> On Thu, Jul 20, 2017 at 10:34 PM, Geordie J via swift-users <
> swift-users@swift.org> wrote:
>
>> Hi all,
>>
>> My team and I are trying to use SwiftPM to develop a relatively complex
>> app with multiple dependencies, all of which are being developed locally
>> and in parallel. The reason for this is compatibility with an existing
>> module/import structure used by our iOS app. Maybe I’m doing something very
>> wrong but my experience so far (2 months in) is that this is extremely
>> difficult with SwiftPM.
>>
>> What I’d love to be able to do is to just run `git add submodule
>> http://blah.com/mysubmodule.git` in the Packages subdirectory and
>> SwiftPM would just let me manage dependencies from there myself.
>>
>> I was excited to see that SwiftPM 4 has a "Top of Tree" development
>> option for this purpose. So far my experience with this has not been good.
>> Firstly because SwiftPM *still* unnecessarily tries to clone my repos
>> itself (some of which are huge), and secondly because this creates an
>> absolute path dependency in `.build/dependencies-state.json`, meaning this
>> setup isn’t sharable within our dev team.
>>
>> Attempting this with "local" git urls adds an almost absurd level of
>> complexity, having to tag each commit for SwiftPM to build. The fact that
>> we'd need to make a commit to test whether the project even builds is
>> insane enough as is, let alone the tagging and trying to tell the base
>> project to use a newer minor version etc etc.
>>
>> Adding multiple subtargets is also not an option because the dependencies
>> (as dynamic libraries) really are shared between multiple
>> targets/sub-dependencies, which SwiftPM seems to deal with quite well.
>>
>> *tldr;* *Please* let us manage dependencies ourselves. It’d be so easy
>> if Package.swift had an option along the lines of *.Package.local(named:
>> "XYZ")* that it then looked for in ./Packages/XYZ. Again, maybe I’m
>> overlooking something but this seems like an obvious and vital option to
>> have. It’d also simplify the introductory SwiftPM docs significantly.
>>
>> Is anyone else having this issue? Would this change really be as simple
>> and painless as it sounds? I would be prepared to make a pull request along
>> these lines.
>>
>
> I think you're not really using the Top of Tree feature. You need to add
> each dependency using its canonical URL, hosted at some server like github.
> After adding the dependencies, you can use edit feature to put a dependency
> in Top of Tree mode. To do so, run:
>
> $ swift package edit  --path
> ../path/to/self/managed/checkout/of/the/package
>
>
> Yes, this is what I tried this week. I’m pretty sure this is not a case of
> misunderstanding the feature or the docs.
>
>
> The package manager will then stop using the cloned repository and use the
> checkout present at that path (regardless of the state it is in).
>
>
> Yes, but then I have – per dependency – two checkouts of a potentially
> huge repository. Why force everyone on the dev team to clone a huge repo
> twice, only to *never* use one of the clones. Also, SwiftPM breaks when
> —path points at Packages/PackageName, which is exactly where I’d expect the
> package to be, not in some arbitrary external path (+ some kind of internal
> checkout cache that will never be used) as well.
>
> I haven’t tried to test this recently because it’s a slow process but I
> have the impression the deps could be even be cloned more than twice,
> depending on how cleverly SwiftPM realises that multiple Packages have the
> same dependency.
>
> Also, this makes managing interdependent state of development amongst
> dependencies more difficult than needed. How do we guarantee that devs are
> on the same commit when using top of tree development? Tagging and managing
> version numbers etc for day-to-day development is emphatically not an
> option for us. Since SwiftPM packages only work from a git context anyway,
> why not allow use of git’s established pattern of dealing with this, namely
> submodules?
>
> Sharing this setup is not automatic, but simple. Each user just needs to
> run the above command once per dependency.
>
>
> We have about 10 dependencies, *all *of which will* always* be in this
> state. This seems like a lot of overhead and room for user error, plus it’s
> a huge workaround for something that could be very simple.
>
> Also, you only need to do this if you're actively working on a dependency.
>
>
> The point is that we will *always* be working on the dependencies. This
> is the core of what we’re doing, not a short aside. This is what makes me
> think we are either doing something wrong, or there is a big feature gap
> (as it appears from here).
>
> The new manifest also supports using branch instead of version range,
> which is very helpful during 

Re: [swift-users] Should I be using more catchless do blocks?

2017-06-20 Thread Geordie Jay via swift-users
Sorry in advance if Google Inbox messes with my code formatting below
(can't there be just one good email client? I miss Mailbox)

Michael Savich via swift-users  schrieb am Mo. 19.
Juni 2017 um 20:54:

> Yeah, it's all about balance to be sure. Though one benefit of do blocks
> is in functions that are tied to a sense of time. It seems to me that the
> in case of something like viewDidLoad separating code into too many
> functions can obscure the fact that the code is meant to be executed at
> that time.
>

In my experience, the most idiomatic and readable (and testable! if that's
important in your context) way of doing this is to create extensions to
group and encapsulate related functionality (example obviously won't
compile but hopefully you get what I mean):

```
extension MyViewController {
override public func viewDidLoad() {
let something = processModelData(data)
let views = something.map { UIView($0) }
addRelatedSubviews(view)
}

private func addRelatedSubviews() {...}
private func processModelData() {...}
}
```

Closures can provide much of the same functionality but I'm pretty sure
> inline closures have to have names and sometimes risking a bad name is
> worse than no name at all.
>
> Anyway, do you think that most Swift users are even aware that do can be
> used in this fashion?
>

Yes, and sometimes it's useful, most of the time I've seen or used it
myself I'd consider it a code smell.

This is just a personal preference but I find that more indentation is
almost always harder to read than less. The aim is to reduce cognitive load
("Don't make me think").


>
> Sent from my iPad
>
> On Jun 19, 2017, at 2:33 PM, Michael Ilseman  wrote:
>
> Introducing scope to manage lifetimes of local variables is a useful and
> valuable practice. Note that it might also be an opportunity to refactor
> the code. Any do block you want to introduce could also be a local function
> definition that you call later. Alternatively, it could be generalized and
> extracted into a utility component. Long function bodies with many do
> blocks could be a code smell.
>
>
> On Jun 18, 2017, at 7:07 PM, Michael Savich via swift-users <
> swift-users@swift.org> wrote:
>
> So, something I did not know until recently is that do blocks in Swift are
> for more than just error handling, they can also be used to tighten scope.
>
> I'm wondering, why *not* use a ton of do blocks? Like, if I have a
> ViewController lifecycle method like viewDidLoad, I could segment it into
> out a do block for creating subviews, a do block for loading data into
> them, and a do block for adding them to the view itself. This seems like it
> would enforce grouping code tightly together.
>
> Yes I could adopt a functional style of programming, but that has its
> downsides too, namely reading any functional code involves trawling through
> a long sequence of function calls. What I'm saying is, do blocks seem like
> a way to get many of the benefits of functional programming while
> maintaining the readability of imperative code. (Sorry functional
> programmers, I promise I love Haskell too!)
>
> So I guess what I'm saying is… somebody talk me down from this ledge. Is
> there a reason I *shouldn't *refactor my projects to be full of do
> blocks? And can this usage of do really be considered idiomatic Swift? Or
> will most people reading my code be left wondering where all the try and
> catch statements are?
>
> Sent from my iPad
> ___
> 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] Compile time exceeded. Anything wrong?

2017-06-05 Thread Geordie Jay via swift-users
I doubt it'll be "fixed" in the next release (which came out less than 24
hours ago), but I gather type checker speed optimisations and fixing
crashes are ongoing goals of the compiler team. With no guarantees or
expectations, you may find your code compiles in an acceptable time with
Swift 4 (Xcode 9).

Cheers,
Geordie
On Tue 6. Jun 2017 at 12:29,  wrote:

> thanks,  guys!  dp array should be var, not let, but the compile run too
> slow. It indeed a bug.  Optimizing  the code for the compiling time is
> really a headache for coders.  I am using the Xcode 8.1. Hoping it can be
> fixed in next release.
>
>
> *best wishes for you *
>
> 2017-06-06 8:57 GMT+08:00 Geordie J :
>
>>
>> Am 06.06.2017 um 09:02 schrieb Jens Persson via swift-users <
>> swift-users@swift.org>:
>>
>> When compiling that from the command line, I get the following (after
>> about 6 seconds):
>>
>> test.swift:7:18: error: cannot assign through subscript: 'dp' is a 'let'
>> constant
>> dp[0][0] = 0
>> ~~   ^
>> /.../
>>
>> After fixing that (changing let dp to var dp), it will compile
>> successfully, still taking a very long time though. This usually means that
>> some expression(s) in the code happen to be a bit hard on the type checker
>> (in its current state).
>> I tried the latest dev snapshot and it is a bit faster, perhaps 3 s
>> instead of 6.
>>
>> Anyway, here is a logically equivalent rewrite which will compile faster:
>>
>> class Solution {
>> func rob(nums: [Int]) -> Int {
>> guard nums.count > 0 else { return 0 }
>> var dp = Array.init(repeating: Array.init(repeating: 0, count:
>> nums.count),
>> count: 2)
>> dp[0][0] = 0
>> dp[0][1] = nums[0]
>> for i in 1 ..< nums.count {
>>   let dp_iMinus1_0 = dp[i - 1][0]
>>   let dp_iMinus1_1 = dp[i - 1][1]
>> dp[i][0] = max(dp_iMinus1_0, dp_iMinus1_1)
>> dp[i][1] = dp_iMinus1_0 + nums[i]
>>
>>
>> Just a nitpick: this isn’t functionally equivalent to the original code
>> (dp[i][1] = dp[i][0] + nums[i]), because dp[i][0] might have actually
>> changed on the previous line. But you can return this line to the original
>> version without any effect on the compile time (less than 250ms on my
>> machine).
>>
>> I think the compile time issue is that max() is a generic function that
>> takes any Comparable, so the type checker seems to go berserk trying to
>> ensure the term is satisfiable.
>>
>> If you create a non-generic replacement for max in the same file:
>>
>> private func myMax(_ x1: Int, _ x2: Int) -> Int {
>> return (x1 >= x2) ? x1 : x2
>> }
>>
>> … and replace the assignment to *max(dp[i - 1][0], ……)* in the for loop
>> with *myMax(dp[i - 1][0], ….)*
>>
>> The compile time will be just as fast as the one that swaps out the
>> internal elements (on my machine it’s actually about 10% faster with the
>> non-generic *max*).
>>
>> Regards,
>> Geordie
>>
>> }
>> return 0
>> }
>> }
>>
>>
>>
>>
>>
>> On Mon, Jun 5, 2017 at 2:32 PM, Hbucius Smith via swift-users <
>> swift-users@swift.org> wrote:
>>
>>> Hi Swift-Users,
>>>
>>> when I compiled the code, Xcode cannot stop, I do not know why. It
>>> is very strange. Can anyone help ? Here is the code. I am using Xcode 8.1
>>>
>>> class Solution {
>>>
>>> func rob(nums: [Int]) -> Int {
>>>
>>> guard nums.count > 0 else { return 0 }
>>>
>>> let dp = Array.init(repeating: Array.init(repeating: 0, count:
>>> nums.count),
>>>
>>> count: 2)
>>>
>>> dp[0][0] = 0
>>>
>>> dp[0][1] = nums[0]
>>>
>>> for i in 1 ..< nums.count {
>>>
>>> dp[i][0] = max(dp[i - 1][0], dp[i - 1][1])
>>>
>>> dp[i][1] = dp[i - 1][0] + nums[i]
>>>
>>> }
>>>
>>> return 0
>>>
>>> }
>>>
>>> }
>>>
>>>
>>>
>>> *best wishes for you *
>>>
>>> ___
>>> 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] Calling default implementation of protocol methods as selectors

2017-06-03 Thread Geordie Jay via swift-users
That's why I thanked for for the amendment. As I said, typing code blindly
on the phone, mistakes are inevitable. Thanks for clearing it up.
On Sun 4. Jun 2017 at 15:04, Zhao Xin  wrote:

> I was not talking about the formatting. I am talking about the
> implementation.
>
> You can't use `self` before you call `super.init` as you did now. If
>  changing your implementation to called `super.init` and then call `self`
> in `super.init` again. You would have called `super.init` twice. I don't
> know what that means. But it smells bad.
>
> Zhaoxin
>
> On Sun, Jun 4, 2017 at 12:51 PM, Geordie Jay  wrote:
>
>> Thanks for the amendment, and sorry for the (lack of) formatting. I
>> painstakingly typed that on my phone with manually-spaced indenting, which
>> the Inbox app unhelpfully removed entirely when I pressed send. Pasting
>> into Xcode should do the trick though..
>>
>> Geordie
>>
>> On Sun 4. Jun 2017 at 14:49, Zhao Xin  wrote:
>>
>>> You should change to another way. Using `self` in `super.init` is not
>>> allowed.
>>>
>>> Zhaoxin
>>>
>>> On Sun, Jun 4, 2017 at 12:38 PM, Geordie Jay  wrote:
>>>
 I am dealing with a variant of this on Android right now. I have just
 subclassed e.g. UITapGestureRecognizer to perform the 2nd variant above and
 externally accept a closure as its argument. I'm writing this on my phone
 so forgive any syntax errors or accidental omissions:

 class TapGestureRecognizer: UITapGestureRecognizer {
 var onTap: (() -> Void)?
 init(onTap: (() -> Void)?) {
 self.onTap = onTap
 super.init(target: self, action: #selector(internalTapHandler))
 }

 @objc private func internalTapHandler() {
 onTap?()
 }
 }

 class Baz: Foo {
 init() {
 let tapRecognizer = TapGestureRecognizer(onTap: self.bar)
 }
 }


 Cheers,
 Geordie

 On Sat 3. Jun 2017 at 16:53, Nate Birkholz via swift-users <
 swift-users@swift.org> wrote:

> Thanks, the second had occurred to me, but felt a little too much like
> in practice it would make the code harder to understand.
>
> On Fri, Jun 2, 2017 at 9:58 PM, Zhao Xin  wrote:
>
>> I found two workarounds.
>>
>> 1.
>>
>> protocol Foo: class {
>>
>> func bar()
>>
>> }
>>
>>
>> class Base:Foo {
>>
>> @objc func bar() {
>>
>> print("bar")
>>
>> }
>>
>> }
>>
>>
>> class Baz: Base {
>>
>> override init() {
>>
>> super.init()
>>
>> let tapRecognizer = UITapGestureRecognizer(target: self,
>> action: #selector(bar))
>>
>> }
>>
>> }
>>
>> 2.
>>
>> protocol Foo: class {
>>
>> func bar()
>>
>> }
>>
>>
>> extension Foo {
>>
>> func bar() {
>>
>> print("bar")
>>
>> }
>>
>> }
>>
>>
>> class Baz: Foo {
>>
>> init() {
>>
>> let tapRecognizer = UITapGestureRecognizer(target: self,
>> action: #selector(delegate))
>>
>> }
>>
>>
>>
>> @objc func delegate() {
>>
>> bar()
>>
>> }
>>
>> }
>>
>>
>> Zhao Xin
>>
>>
>>
>>
>>
>>
>> On Sat, Jun 3, 2017 at 10:35 AM, Nate Birkholz via swift-users <
>> swift-users@swift.org> wrote:
>>
>>> protocol Foo: class {
>>> func bar()
>>> }
>>>
>>> extension Foo {
>>> func bar() {
>>>  print("bar")
>>> }
>>> }
>>>
>>> class Baz: Foo {
>>> init() {
>>> let tapRecognizer = UITapGestureRecognizer(target: self,
>>> action: #selector(bar))
>>> }
>>> }
>>>
>>> the #selector tells me: "Argument of '#selector' refers to instance
>>> method 'bar()' that is not exposed to Objective-C" and asks me to add 
>>> @objc
>>> to the method definition.
>>>
>>> Adding @objc to the method tells me: "@objc can only be used with
>>> members of classes, @objc protocols, and concrete extensions of classes"
>>>
>>> Adding @objc to the protocol doesn't fix it, just introduces new
>>> issues.
>>>
>>> "dynamic" cannot be applied to a protocol, so cannot be used
>>> alternatively.
>>>
>>> Is there a way to get around this? If a method is called by a
>>> gesture recognizer, is there no way to have a default protocol
>>> implementation? I'd like to use default implementations if possible to 
>>> make
>>> my code more DRY.
>>>
>>> Is there a roadmap/plan for swift-native selector dispatch?
>>>
>>> Thanks. I look forward to the inevitable reply revealing the dumb
>>> thing I missed. :)
>>>
>>> --
>>> Nate Birkholz
>>>
>>> ___
>>> swift-users mailing list
>>> swift-use

Re: [swift-users] Calling default implementation of protocol methods as selectors

2017-06-03 Thread Geordie Jay via swift-users
Thanks for the amendment, and sorry for the (lack of) formatting. I
painstakingly typed that on my phone with manually-spaced indenting, which
the Inbox app unhelpfully removed entirely when I pressed send. Pasting
into Xcode should do the trick though..

Geordie
On Sun 4. Jun 2017 at 14:49, Zhao Xin  wrote:

> You should change to another way. Using `self` in `super.init` is not
> allowed.
>
> Zhaoxin
>
> On Sun, Jun 4, 2017 at 12:38 PM, Geordie Jay  wrote:
>
>> I am dealing with a variant of this on Android right now. I have just
>> subclassed e.g. UITapGestureRecognizer to perform the 2nd variant above and
>> externally accept a closure as its argument. I'm writing this on my phone
>> so forgive any syntax errors or accidental omissions:
>>
>> class TapGestureRecognizer: UITapGestureRecognizer {
>> var onTap: (() -> Void)?
>> init(onTap: (() -> Void)?) {
>> self.onTap = onTap
>> super.init(target: self, action: #selector(internalTapHandler))
>> }
>>
>> @objc private func internalTapHandler() {
>> onTap?()
>> }
>> }
>>
>> class Baz: Foo {
>> init() {
>> let tapRecognizer = TapGestureRecognizer(onTap: self.bar)
>> }
>> }
>>
>>
>> Cheers,
>> Geordie
>>
>> On Sat 3. Jun 2017 at 16:53, Nate Birkholz via swift-users <
>> swift-users@swift.org> wrote:
>>
>>> Thanks, the second had occurred to me, but felt a little too much like
>>> in practice it would make the code harder to understand.
>>>
>>> On Fri, Jun 2, 2017 at 9:58 PM, Zhao Xin  wrote:
>>>
 I found two workarounds.

 1.

 protocol Foo: class {

 func bar()

 }


 class Base:Foo {

 @objc func bar() {

 print("bar")

 }

 }


 class Baz: Base {

 override init() {

 super.init()

 let tapRecognizer = UITapGestureRecognizer(target: self,
 action: #selector(bar))

 }

 }

 2.

 protocol Foo: class {

 func bar()

 }


 extension Foo {

 func bar() {

 print("bar")

 }

 }


 class Baz: Foo {

 init() {

 let tapRecognizer = UITapGestureRecognizer(target: self,
 action: #selector(delegate))

 }



 @objc func delegate() {

 bar()

 }

 }


 Zhao Xin






 On Sat, Jun 3, 2017 at 10:35 AM, Nate Birkholz via swift-users <
 swift-users@swift.org> wrote:

> protocol Foo: class {
> func bar()
> }
>
> extension Foo {
> func bar() {
>  print("bar")
> }
> }
>
> class Baz: Foo {
> init() {
> let tapRecognizer = UITapGestureRecognizer(target: self,
> action: #selector(bar))
> }
> }
>
> the #selector tells me: "Argument of '#selector' refers to instance
> method 'bar()' that is not exposed to Objective-C" and asks me to add 
> @objc
> to the method definition.
>
> Adding @objc to the method tells me: "@objc can only be used with
> members of classes, @objc protocols, and concrete extensions of classes"
>
> Adding @objc to the protocol doesn't fix it, just introduces new
> issues.
>
> "dynamic" cannot be applied to a protocol, so cannot be used
> alternatively.
>
> Is there a way to get around this? If a method is called by a gesture
> recognizer, is there no way to have a default protocol implementation? I'd
> like to use default implementations if possible to make my code more DRY.
>
> Is there a roadmap/plan for swift-native selector dispatch?
>
> Thanks. I look forward to the inevitable reply revealing the dumb
> thing I missed. :)
>
> --
> Nate Birkholz
>
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users
>
>

>>>
>>>
>>> --
>>> Nate Birkholz
>>> ___
>>> 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] Calling default implementation of protocol methods as selectors

2017-06-03 Thread Geordie Jay via swift-users
I am dealing with a variant of this on Android right now. I have just
subclassed e.g. UITapGestureRecognizer to perform the 2nd variant above and
externally accept a closure as its argument. I'm writing this on my phone
so forgive any syntax errors or accidental omissions:

class TapGestureRecognizer: UITapGestureRecognizer {
var onTap: (() -> Void)?
init(onTap: (() -> Void)?) {
self.onTap = onTap
super.init(target: self, action: #selector(internalTapHandler))
}

@objc private func internalTapHandler() {
onTap?()
}
}

class Baz: Foo {
init() {
let tapRecognizer = TapGestureRecognizer(onTap: self.bar)
}
}


Cheers,
Geordie
On Sat 3. Jun 2017 at 16:53, Nate Birkholz via swift-users <
swift-users@swift.org> wrote:

> Thanks, the second had occurred to me, but felt a little too much like in
> practice it would make the code harder to understand.
>
> On Fri, Jun 2, 2017 at 9:58 PM, Zhao Xin  wrote:
>
>> I found two workarounds.
>>
>> 1.
>>
>> protocol Foo: class {
>>
>> func bar()
>>
>> }
>>
>>
>> class Base:Foo {
>>
>> @objc func bar() {
>>
>> print("bar")
>>
>> }
>>
>> }
>>
>>
>> class Baz: Base {
>>
>> override init() {
>>
>> super.init()
>>
>> let tapRecognizer = UITapGestureRecognizer(target: self, action:
>> #selector(bar))
>>
>> }
>>
>> }
>>
>> 2.
>>
>> protocol Foo: class {
>>
>> func bar()
>>
>> }
>>
>>
>> extension Foo {
>>
>> func bar() {
>>
>> print("bar")
>>
>> }
>>
>> }
>>
>>
>> class Baz: Foo {
>>
>> init() {
>>
>> let tapRecognizer = UITapGestureRecognizer(target: self, action:
>> #selector(delegate))
>>
>> }
>>
>>
>>
>> @objc func delegate() {
>>
>> bar()
>>
>> }
>>
>> }
>>
>>
>> Zhao Xin
>>
>>
>>
>>
>>
>>
>> On Sat, Jun 3, 2017 at 10:35 AM, Nate Birkholz via swift-users <
>> swift-users@swift.org> wrote:
>>
>>> protocol Foo: class {
>>> func bar()
>>> }
>>>
>>> extension Foo {
>>> func bar() {
>>>  print("bar")
>>> }
>>> }
>>>
>>> class Baz: Foo {
>>> init() {
>>> let tapRecognizer = UITapGestureRecognizer(target: self, action:
>>> #selector(bar))
>>> }
>>> }
>>>
>>> the #selector tells me: "Argument of '#selector' refers to instance
>>> method 'bar()' that is not exposed to Objective-C" and asks me to add @objc
>>> to the method definition.
>>>
>>> Adding @objc to the method tells me: "@objc can only be used with
>>> members of classes, @objc protocols, and concrete extensions of classes"
>>>
>>> Adding @objc to the protocol doesn't fix it, just introduces new issues.
>>>
>>> "dynamic" cannot be applied to a protocol, so cannot be used
>>> alternatively.
>>>
>>> Is there a way to get around this? If a method is called by a gesture
>>> recognizer, is there no way to have a default protocol implementation? I'd
>>> like to use default implementations if possible to make my code more DRY.
>>>
>>> Is there a roadmap/plan for swift-native selector dispatch?
>>>
>>> Thanks. I look forward to the inevitable reply revealing the dumb thing
>>> I missed. :)
>>>
>>> --
>>> Nate Birkholz
>>>
>>> ___
>>> swift-users mailing list
>>> swift-users@swift.org
>>> https://lists.swift.org/mailman/listinfo/swift-users
>>>
>>>
>>
>
>
> --
> Nate Birkholz
> ___
> 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] Annotating C APIs without changing the original header files

2017-05-14 Thread Geordie Jay via swift-users
Cheers,
Geordie


Daniel Dunbar  schrieb am Fr. 12. Mai 2017 um
20:33:

> We don't have explicit support for api notes in SwiftPM.
>

Does that mean there is "unexplicit" support (maybe via swift build command
line arguments)?

I don't mind if I have to make a build script, but it'd be a major code
compatibility issue across the supported platforms if apinotes didn't work
at all on Linux.


> We discussed it, and it something which probably makes sense, but no one
> has worked on a design or implementation yet.
>
>  - Daniel
>
> On May 12, 2017, at 11:32 AM, Michael Gottesman via swift-users <
> swift-users@swift.org> wrote:
>
> +Ankit
>
> Michael
>
> On May 12, 2017, at 10:10 AM, Geordie J via swift-users <
> swift-users@swift.org> wrote:
>
> To continue this thread: I managed to annotate a bunch of C APIs with
> modulename.apinotes. This works with Xcode (to a certain degree - pointers,
> enums, and especially OpaquePointers are tricky). I’m now trying to build
> my package with SwiftPM and it doesn’t seem to recognise the apinotes file.
>
> @Doug Gregor, would you be able to advise as to whether apinotes works
> with SwiftPM (on Linux) and whether it requires some extra settings that I
> may be unaware of?
>
> Thanks and best regards for the weekend,
> Geordie
>
>
> Am 08.05.2017 um 00:51 schrieb Geordie Jay :
>
> I'm having the same issue. The renames seem to work, as in they disappear
> from the global scope with a fixit to rename to the new (namespaced)
> version if I type in the name manually, but they don't appear as static
> members of the enum type, regardless of how I call them. Would appreciate
> some help with this too.
>
> Cheers,
> Geordie
> Rick Mann  schrieb am So. 7. Mai 2017 um 23:06:
>
>> I'm trying to use apinotes for this third-party C library (call it
>> "Lib.dylib"). It has an enum lgs_error_t:
>>
>> typedef enum {
>> lgs_error_none = 0,
>> lgs_error_invalid_handle = -1,
>> lgs_error_null = -2,
>> lgs_error_invalid_parameter = -3,
>> lgs_error_invalid_operation = -4,
>> lgs_error_queue_full = -5
>> } lgs_error_t;
>>
>> So I wrote apinotes ("Lib.apinotes") that look like this, next to the
>> .dylib, and part of my Xcode iOS app target:
>>
>> Enumerators:
>> # lgs_error_t
>>
>> - Name: lgs_error_none
>>   SwiftName: lgs_error_t.none
>> - Name: lgs_error_invalid_handle
>>   SwiftName: lgs_error_t.invalidHandle
>> - Name: lgs_error_null
>>   SwiftName: lgs_error_t.nullParameter
>> - Name: lgs_error_invalid_parameter
>>   SwiftName: lgs_error_t.invalideParameter
>> - Name: lgs_error_invalid_operation
>>   SwiftName: lgs_error_t.invalidOperation
>> - Name: lgs_error_queue_full
>>   SwiftName: lgs_error_t.queueFull
>>
>> But this line of code fails:
>>
>> var err: lgs_error_t = .nullParameter
>> Type 'lgs_error_t' has no member 'nullParameter'
>>
>> Am I missing something else?
>>
>> > On May 4, 2017, at 16:55 , Douglas Gregor via swift-users <
>> swift-users@swift.org> wrote:
>> >
>> >
>> >> On May 3, 2017, at 4:10 PM, Geordie J via swift-users <
>> swift-users@swift.org> wrote:
>> >>
>> >> Hi everyone,
>> >>
>> >> I’m about to start on another big project with Swift on Android and
>> would like to annotate that JNI headers as much as possible before I do:
>> specifically I’d like to make _Nonnull and CF_SWIFT_NAME annotations to the
>> headers found in a user's jni.h.
>> >>
>> >> The question is: is it possible to annotate headers this without
>> changing the original header files? Specifically I’m looking for an options
>> that allows annotations in a separate file, probably one that is read when
>> loading the package’s module.modulemap.
>> >>
>> >> I’d like to distribute the annotations in a SwiftPM package that also
>> exposes the original (hopefully annotated) headers. Up until now I’ve been
>> using Swift to override methods in code, but this isn’t as clean or
>> extensible and I fear it may have other (particularly performance)
>> implications.
>> >>
>> >> I guess the alternative would be to just maintain and distribute a
>> modified version of jni.h with the annotations, but that would be a "last
>> resort” option.
>> >
>> >
>> > This is the role of API notes, which you can see here:
>> >
>> >   https://github.com/apple/swift/tree/master/apinotes
>> >
>> > with some rough documentation-in-source here:
>> >
>> >
>> https://github.com/apple/swift-clang/blob/stable/lib/APINotes/APINotesYAMLCompiler.cpp
>> >
>> >   - Doug
>> >
>> > ___
>> > swift-users mailing list
>> > swift-users@swift.org
>> > https://lists.swift.org/mailman/listinfo/swift-users
>>
>>
>> --
>> Rick Mann
>> rm...@latencyzero.com
>>
>>
>>
> ___
> 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/swif

Re: [swift-users] Annotating C APIs without changing the original header files

2017-05-07 Thread Geordie Jay via swift-users
I'm having the same issue. The renames seem to work, as in they disappear
from the global scope with a fixit to rename to the new (namespaced)
version if I type in the name manually, but they don't appear as static
members of the enum type, regardless of how I call them. Would appreciate
some help with this too.

Cheers,
Geordie
Rick Mann  schrieb am So. 7. Mai 2017 um 23:06:

> I'm trying to use apinotes for this third-party C library (call it
> "Lib.dylib"). It has an enum lgs_error_t:
>
> typedef enum {
> lgs_error_none = 0,
> lgs_error_invalid_handle = -1,
> lgs_error_null = -2,
> lgs_error_invalid_parameter = -3,
> lgs_error_invalid_operation = -4,
> lgs_error_queue_full = -5
> } lgs_error_t;
>
> So I wrote apinotes ("Lib.apinotes") that look like this, next to the
> .dylib, and part of my Xcode iOS app target:
>
> Enumerators:
> # lgs_error_t
>
> - Name: lgs_error_none
>   SwiftName: lgs_error_t.none
> - Name: lgs_error_invalid_handle
>   SwiftName: lgs_error_t.invalidHandle
> - Name: lgs_error_null
>   SwiftName: lgs_error_t.nullParameter
> - Name: lgs_error_invalid_parameter
>   SwiftName: lgs_error_t.invalideParameter
> - Name: lgs_error_invalid_operation
>   SwiftName: lgs_error_t.invalidOperation
> - Name: lgs_error_queue_full
>   SwiftName: lgs_error_t.queueFull
>
> But this line of code fails:
>
> var err: lgs_error_t = .nullParameter
> Type 'lgs_error_t' has no member 'nullParameter'
>
> Am I missing something else?
>
> > On May 4, 2017, at 16:55 , Douglas Gregor via swift-users <
> swift-users@swift.org> wrote:
> >
> >
> >> On May 3, 2017, at 4:10 PM, Geordie J via swift-users <
> swift-users@swift.org> wrote:
> >>
> >> Hi everyone,
> >>
> >> I’m about to start on another big project with Swift on Android and
> would like to annotate that JNI headers as much as possible before I do:
> specifically I’d like to make _Nonnull and CF_SWIFT_NAME annotations to the
> headers found in a user's jni.h.
> >>
> >> The question is: is it possible to annotate headers this without
> changing the original header files? Specifically I’m looking for an options
> that allows annotations in a separate file, probably one that is read when
> loading the package’s module.modulemap.
> >>
> >> I’d like to distribute the annotations in a SwiftPM package that also
> exposes the original (hopefully annotated) headers. Up until now I’ve been
> using Swift to override methods in code, but this isn’t as clean or
> extensible and I fear it may have other (particularly performance)
> implications.
> >>
> >> I guess the alternative would be to just maintain and distribute a
> modified version of jni.h with the annotations, but that would be a "last
> resort” option.
> >
> >
> > This is the role of API notes, which you can see here:
> >
> >   https://github.com/apple/swift/tree/master/apinotes
> >
> > with some rough documentation-in-source here:
> >
> >
> https://github.com/apple/swift-clang/blob/stable/lib/APINotes/APINotesYAMLCompiler.cpp
> >
> >   - Doug
> >
> > ___
> > swift-users mailing list
> > swift-users@swift.org
> > https://lists.swift.org/mailman/listinfo/swift-users
>
>
> --
> Rick Mann
> rm...@latencyzero.com
>
>
>
___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] Annotating C APIs without changing the original header files

2017-05-04 Thread Geordie Jay via swift-users
Fantastic! Thanks for the info, this is great news.

While I have you, I'm interested in annotating function pointers.
Specifically, the JNI environment instance is a pointer to a pointer, so as
is you have to type env.pointee.pointee.FunctionName(env, param1, param2)

Ideally this would just look like env.FunctionName(param1, param2). It's a
long shot but is this goal at all reasonable via annotations alone?

Cheers,
Geordie
Douglas Gregor  schrieb am Fr. 5. Mai 2017 um 01:59:

> On May 4, 2017, at 4:57 PM, Geordie Jay  wrote:
>
> Great, thanks for reminding me of this feature. I couldn't see how it
> could be used outside of the stdlib though, is it possible to use apinotes
> when simply linking a C module via its modulemap ?
>
>
> You can put
>
> .apinotes
>
> into the same directory as the module map.
>
> - Doug
>
> Douglas Gregor  schrieb am Fr. 5. Mai 2017 um 01:55:
>
>>
>> On May 3, 2017, at 4:10 PM, Geordie J via swift-users <
>> swift-users@swift.org> wrote:
>>
>> Hi everyone,
>>
>> I’m about to start on another big project with Swift on Android and would
>> like to annotate that JNI headers as much as possible before I do:
>> specifically I’d like to make _Nonnull and CF_SWIFT_NAME annotations to the
>> headers found in a user's jni.h.
>>
>> The question is: is it possible to annotate headers this without changing
>> the original header files? Specifically I’m looking for an options that
>> allows annotations in a separate file, probably one that is read when
>> loading the package’s module.modulemap.
>>
>> I’d like to distribute the annotations in a SwiftPM package that also
>> exposes the original (hopefully annotated) headers. Up until now I’ve been
>> using Swift to override methods in code, but this isn’t as clean or
>> extensible and I fear it may have other (particularly performance)
>> implications.
>>
>> I guess the alternative would be to just maintain and distribute a
>> modified version of jni.h with the annotations, but that would be a "last
>> resort” option.
>>
>>
>>
>> This is the role of API notes, which you can see here:
>>
>> https://github.com/apple/swift/tree/master/apinotes
>>
>> with some rough documentation-in-source here:
>>
>>
>> https://github.com/apple/swift-clang/blob/stable/lib/APINotes/APINotesYAMLCompiler.cpp
>>
>> - Doug
>>
>>
>
___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] Annotating C APIs without changing the original header files

2017-05-04 Thread Geordie Jay via swift-users
Great, thanks for reminding me of this feature. I couldn't see how it could
be used outside of the stdlib though, is it possible to use apinotes when
simply linking a C module via its modulemap ?
Douglas Gregor  schrieb am Fr. 5. Mai 2017 um 01:55:

>
> On May 3, 2017, at 4:10 PM, Geordie J via swift-users <
> swift-users@swift.org> wrote:
>
> Hi everyone,
>
> I’m about to start on another big project with Swift on Android and would
> like to annotate that JNI headers as much as possible before I do:
> specifically I’d like to make _Nonnull and CF_SWIFT_NAME annotations to the
> headers found in a user's jni.h.
>
> The question is: is it possible to annotate headers this without changing
> the original header files? Specifically I’m looking for an options that
> allows annotations in a separate file, probably one that is read when
> loading the package’s module.modulemap.
>
> I’d like to distribute the annotations in a SwiftPM package that also
> exposes the original (hopefully annotated) headers. Up until now I’ve been
> using Swift to override methods in code, but this isn’t as clean or
> extensible and I fear it may have other (particularly performance)
> implications.
>
> I guess the alternative would be to just maintain and distribute a
> modified version of jni.h with the annotations, but that would be a "last
> resort” option.
>
>
>
> This is the role of API notes, which you can see here:
>
> https://github.com/apple/swift/tree/master/apinotes
>
> with some rough documentation-in-source here:
>
>
> https://github.com/apple/swift-clang/blob/stable/lib/APINotes/APINotesYAMLCompiler.cpp
>
> - Doug
>
>
___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users