Re: [swift-users] raw buffer pointer load alignment

2017-11-10 Thread Joe Groff via swift-users


> On Nov 8, 2017, at 5:41 PM, Kelvin Ma via swift-users  
> wrote:
> 
> yikes there’s no less verbose way to do that? and if the type isn’t an 
> integer there’s no way to avoid the default initialization? Can this be done 
> with opaques or something?

It would be reasonable to put this all in extension methods on UnsafeRawPointer 
for unaligned loads and stores using memcpy(). (The standard library really 
ought to have these at some point.)

-Joe
___
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-04 Thread Joe Groff via swift-users


> On Oct 4, 2017, at 11:02 AM, Ján Kosa via swift-users  
> 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, symbolName)
> 
> 
> 
> if sym != nil {
> 
> let f: InitFunction = unsafeBitCast(sym, to: InitFunction.self)
> 
> let plugin = f() as? PluginInterface
> 
> }
> 
> 
> }
> 
> Package.swift file:
> 
> // swift-tools-version:4.0
> 
> import PackageDescription
> 
> let package = Package(
> 
> name: "PluginConsumer",
> 
> dependencies: [ .package(url: "path_to_plugin_interface", from: "0.0.0") 
> ],
> 
> targets: [ .target(name: "PluginConsumer", dependencies: 
> ["PluginConsumer"]) ]
> 
> 
> )
> 
> 
> 
> This all compiles nicely, MyPlugin project creates dylib file that executable 
> created by PluginConsumer can load, but the problem is with following line:
> 
> let plugin = f() as? PluginInterface
> 
> Type of the plugin is MyPlugin, but from the consumer's view, it doesn't 
> inherit from PluginInterface so I can't call sayHi() method. I assume this is 
> because there is no relation between PluginInterface class that compiler uses 
> for MyPlugin project one that it uses for PluginConsumer project. After 
> library is loaded, they are two completely different classes that happen to 
> share same name. Is my assumption correct and how do I go about fixing it?

It sounds like that may be the case. Class names are namespaced to their 
module. If you're literally including the same PluginInterface.swift file in 
both of your modules, then you're going to end up with a 
ModuleA.PluginInterface and ModuleB.PluginInterface class. If you built 
PluginInterface as its own module, and imported the same module from your 
plugin and host projects, then you should end up with one common class.

-Joe

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


Re: [swift-users] Threads and weak references

2017-09-25 Thread Joe Groff via swift-users


> On Sep 22, 2017, at 2:38 AM, Howard Lovatt via swift-users 
>  wrote:
> 
> Hi,
> 
> I was using a weak reference in a concurrent application and and the main 
> thread wasn't seeing an update to a class's property made by another thread. 
> If I replaced the weak reference with a closure, the problem went away.
> 
> Is there any documentation that describes this behaviour?
> 
> Thanks in advance for any help,

Can you provide a more concrete example of the behavior you're seeing, and the 
behavior you expect?

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


Re: [swift-users] Still can't derive from a generic class

2017-08-31 Thread Joe Groff via swift-users

> On Aug 30, 2017, at 11:17 AM, Joanna Carter via swift-users 
>  wrote:
> 
> Hi Kenny
> 
>> Just curious, and because I have a distinct lack of imagination: can you 
>> share a concrete case of this pattern?

This is likely due to the runtime not handling cycles properly in type metadata 
initialization—a subclass T needs its base class metadata for BaseObject, 
which in turn needs the metadata for T to instantiate the generic type. This is 
something we plan to fix next year since it requires runtime ABI changes. For 
the particular pattern you've described:

> class BaseObject
> {
>  private let properties: [PartialKeyPath : AnyProperty]
> 
>  init(properties: [PartialKeyPath : AnyProperty])
>  {
>self.properties = properties
>  }
> 
>  func value(for keyPath: KeyPath) -> 
> valueType?
>  {
>guard let property = properties[keyPath] else
>{
>  return nil
>}
> 
>return property.getValue()
>  }
> 
>  func set(value: valueType?, for keyPath: KeyPath valueType>)
>  {
>guard let property = properties[keyPath] else
>{
>  return
>}
> 
>property.set(value: value)
>  }
> }
> 
> class Test : BaseObject
> {
>  var name: String?
>  {
>get
>{
>  return value(for: \.name)!
>}
>set
>{
>  set(value: newValue, for: \.name)
>}
>  }
> 
>  var number: Int?
>  {
>get
>{
>  return value(for: \.number)!
>}
>set
>{
>  set(value: newValue, for: \.number)
>}
>  }
> 
>  init()
>  {
>super.init(properties: [\Test.name : Property(), \Test.number : 
> Property()])
>  }
> }
> 
> Without the generic rootType parameter, all the getter and setter methods 
> need an explicit mention of the derived class for the keypath :
> 
> class Test : BaseObject
> {
>  var name: String?
>  {
>get
>{
>  return value(for: \Test.name)!
>}
>set
>{
>  set(value: newValue, for: \Test.name)
>}
>  }
> 
>  …
> }

Would a protocol-based approach suffice? `Self` in a protocol extension would 
give you access to the concrete type in a similar way:

protocol Base: AnyObject {
  var properties:  [PartialKeyPath : AnyProperty] { get }
}

extension Base {
  func value(for keyPath: KeyPath) -> T?
  {
guard let property = properties[keyPath] else
{
  return nil
}

return property.getValue()
  }

  /*etc.*/
}

class Test: Base {
  let properties = [\Test.name: Property()]

  var name: String {
get { return value(for: \.name) }
set { set(value: newValue, for: \.name) }
  }
}

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


Re: [swift-users] Using #function causes big memory leak

2017-08-28 Thread Joe Groff via swift-users

> On Aug 28, 2017, at 11:07 AM, Edward Connell  wrote:
> 
> I reported it 5/16 in bug reporter. Possibly that was the wrong DB?
> 
> https://bugreport.apple.com/web/?problemID=26535526 
> 
> 

No, that's correct. Thanks!

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


Re: [swift-users] Using #function causes big memory leak

2017-08-28 Thread Joe Groff via swift-users

> On Aug 27, 2017, at 10:57 AM, Edward Connell via swift-users 
>  wrote:
> 
> import Foundation
> 
> class A {
>   var counter = 0 {
> //didSet { onSet("counter") }  // no leak
>   didSet { onSet() }  // huge leak
>   }
> 
>   var properties = ["counter" : 0]
>   func onSet(_ name: String = #function) {
>   properties[name]! += 1
>   }
> }
> 
> var myclass = A()
> 
> for i in 0..<1000 {
>   myclass.counter = i
> }
> 
> print(myclass.properties["counter"]!)

The only code generation difference I see, if I modify your didSet to make both 
calls is that the compiler treats #function as a UTF-16 literal, whereas 
"counter" is recognized as an ASCII literal:

// A.counter.didset
sil hidden @_T03foo1AC7counterSifW : $@convention(method) (Int, @guaranteed A) 
-> () {
// %0 // user: %2
// %1 // users: %19, %12, %11, %4, 
%3
bb0(%0 : $Int, %1 : $A):
  debug_value %0 : $Int, let, name "oldValue", argno 1 // id: %2
  debug_value %1 : $A, let, name "self", argno 2  // id: %3
  %4 = class_method %1 : $A, #A.onSet!1 : (A) -> (String) -> (), 
$@convention(method) (@owned String, @guaranteed A) -> () // user: %11
  %5 = string_literal utf8 "counter"  // user: %10
  %6 = integer_literal $Builtin.Word, 7   // user: %10
  %7 = integer_literal $Builtin.Int1, -1  // user: %10
  %8 = metatype $@thin String.Type// user: %10
  // function_ref String.init(_builtinStringLiteral:utf8CodeUnitCount:isASCII:)
  %9 = function_ref 
@_T0S2SBp21_builtinStringLiteral_Bw17utf8CodeUnitCountBi1_7isASCIItcfC : 
$@convention(method) (Builtin.RawPointer, Builtin.Word, Builtin.Int1, @thin 
String.Type) -> @owned String // user: %10
  %10 = apply %9(%5, %6, %7, %8) : $@convention(method) (Builtin.RawPointer, 
Builtin.Word, Builtin.Int1, @thin String.Type) -> @owned String // user: %11
  %11 = apply %4(%10, %1) : $@convention(method) (@owned String, @guaranteed A) 
-> ()
  %12 = class_method %1 : $A, #A.onSet!1 : (A) -> (String) -> (), 
$@convention(method) (@owned String, @guaranteed A) -> () // user: %19
  %13 = string_literal utf16 "counter"// user: %18
  %14 = integer_literal $Builtin.Word, 7  // user: %18
  %15 = integer_literal $Builtin.Int1, -1
  %16 = metatype $@thin String.Type   // user: %18
  // function_ref String.init(_builtinUTF16StringLiteral:utf16CodeUnitCount:)
  %17 = function_ref 
@_T0S2SBp26_builtinUTF16StringLiteral_Bw18utf16CodeUnitCounttcfC : 
$@convention(method) (Builtin.RawPointer, Builtin.Word, @thin String.Type) -> 
@owned String // user: %18
  %18 = apply %17(%13, %14, %16) : $@convention(method) (Builtin.RawPointer, 
Builtin.Word, @thin String.Type) -> @owned String // user: %19
  %19 = apply %12(%18, %1) : $@convention(method) (@owned String, @guaranteed 
A) -> ()
  %20 = tuple ()  // user: %21
  return %20 : $()// id: %21
} // end sil function '_T03foo1AC7counterSifW'

Michael, could there be a leak in the implementation of 
String(_builtinUTF16StringLiteral:utf16CodeUnitCount:)? The SIL at first glance 
looks balanced here.

-Joe

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


Re: [swift-users] Using #function causes big memory leak

2017-08-28 Thread Joe Groff via swift-users

> On Aug 27, 2017, at 10:57 AM, Edward Connell via swift-users 
>  wrote:
> 
> I reported this about a year ago, but it has never been fixed and it seems 
> like it should be fixed for the Swift 4.0 release.

What was the SR or radar number?

-Joe

> 
> Here is a simple repro case. If you watch the memory monitor as it runs, you 
> see memory consumption climb to 2.7GB when using #function, and no memory 
> increase when using a static string.
> 
> import Foundation
> 
> class A {
>   var counter = 0 {
> //didSet { onSet("counter") }  // no leak
>   didSet { onSet() }  // huge leak
>   }
> 
>   var properties = ["counter" : 0]
>   func onSet(_ name: String = #function) {
>   properties[name]! += 1
>   }
> }
> 
> var myclass = A()
> 
> for i in 0..<1000 {
>   myclass.counter = i
> }
> 
> print(myclass.properties["counter"]!)
> 
> ___
> 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] Law of Exclusivity runtime false positive?

2017-07-28 Thread Joe Groff via swift-users

> On Jul 28, 2017, at 12:06 AM, David Hart via swift-users 
>  wrote:
> 
> Hello,
> 
> Indeed, I had reduced the code too much. John McCall was kind enough to have 
> a look and here’s the offending code:
> 
> func layoutHorizontally(leftRect: inout CGRect, rightRect: inout CGRect) {
> let totalWidth = imageRect.size.width + titleRect.size.width + 
> contentSpacing
> rightRect.origin.x = leftRect.maxX + contentSpacing
> }
> 
> The problem is that imageRect and titleRect are referenced both directly and 
> in the inout parameters.
> 
> But there’s something I’m not understanding. I went back to the ownership 
> manifesto and re-read the law of exclusivity to make sure I understand it:
> 
> If a storage reference expression evaluates to a storage reference that is 
> implemented by a variable, then the formal access duration of that access may 
> not overlap the formal access duration of any other access to the same 
> variable unless both accesses are reads.
> 
> So I tried to write a test to trigger the runtime error, but was unsuccessful:
> 
> class MyClass {
> var p: CGRect = .zero
> }
> 
> func trigger(a: MyClass, b: MyClass) {
> a.p = b.p
> }
> 
> let m = MyClass()
> trigger(a: m, b: m)
> 
> Here, a storage reference expression (a.p) evaluates to a storage reference 
> that is implemented by a variable (the p property of an instance m of 
> MyClass) and its formal access duration (the trigger function) overlaps the 
> formal access duration of another access to the same variable (through the 
> b.p storage reference expression) and both accesses are not reads (a.p is on 
> the LHS of an assignment).
> 
> Why does this not trigger the Law of Exclusivity?

`b.p` is loaded before `a.p` is written to, so the accesses do not overlap even 
when a === b. Something like swap(, ) (using the Swift 3 global 
definition of 'swap') would trigger an exclusivity trap when a === b, since the 
access to storage passed as an inout argument needs to last for the duration of 
the call.

-Joe

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


Re: [swift-users] What is up with names not being Strings any more in Swift 4?

2017-07-17 Thread Joe Groff via swift-users

> On Jul 17, 2017, at 9:04 AM, Manfred Schubert  wrote:
> 
> 
>> Am 17.07.2017 um 17:47 schrieb Joe Groff :
>> 
>> Yeah, this is the intended use pattern for these namespaced constant. You 
>> don't need the `rawValue:` label, though:
>> 
>> extension NSImage.Name {
>> static let myImage = Name("myImage")
>> }
> 
> It would be possible to do the same thing as an extension to String without 
> making the default/simple case more complicated. So I would have said this is 
> overkill, but I'm fine with it.

By making it a separate type, though, it lets you define constants without 
polluting String's namespace, and lets the type system prevent typos or 
accidental misuse of a name.

> 
> What remains is the question whether it is possible to create NSBindingNames 
> in a safe way, like from #selector().

If you want to ensure that the string value corresponds to a declaration, maybe 
you could use #keyPath, which ought to be interchangeable with a string literal 
but checked by the compiler.

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


Re: [swift-users] What is up with names not being Strings any more in Swift 4?

2017-07-17 Thread Joe Groff via swift-users

> On Jul 17, 2017, at 8:26 AM, Jon Shier via swift-users 
>  wrote:
> 
>   Like Notification.Name, I believe those types are supposed to help you 
> namespace your string constants when you access them. I’d recommend using a 
> code gen tool to generate them from your image assets, like:
> 
> extension NSImage.Name {
>   static let customImage = NSImage.Name(rawValue: “customImage”)
> }
> 
> Which can then be used like: NSImage(named: .customImage). That’s the 
> ultimate use goal. It does make the old code awkward and a pain to migrate 
> though.

Yeah, this is the intended use pattern for these namespaced constant. You don't 
need the `rawValue:` label, though:

extension NSImage.Name {
  static let myImage = Name("myImage")
}

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


Re: [swift-users] Is '_ = x' guaranteed to hold a reference to x?

2017-06-30 Thread Joe Groff via swift-users

> On Jun 30, 2017, at 12:25 PM, Mike Ferenduros  
> wrote:
> 
> Ah, I think I was unclear - I want to extend the lifetime into an escaping 
> closure, not just within a scope, and I was wondering what the minimal way is 
> to do that.

I see. Using `withExtendedLifetime` inside the closure still ought to guarantee 
that the closure captures the variable, and will have the effect of keeping it 
alive till the closure dies.

-Joe

>> On 30 Jun 2017, at 22:15, Joe Groff  wrote:
>> 
>> 
>>> On Jun 30, 2017, at 12:13 PM, Mike Ferenduros  
>>> wrote:
>>> 
>>> With an empty body, you mean?
>> 
>> I'd say it's probably more readable to nest the code that's dependent on the 
>> lifetime of the object in the block body, though you can just put 
>> `withExtendedLifetime(x) { }` at the end of the region (or `defer { 
>> withExtendedLifetime... }` at the beginning) if you can't have the nesting 
>> for whatever reason.
>> 
>> -Joe
>> 
 On 30 Jun 2017, at 22:00, Joe Groff  wrote:
 
 
> On Jun 30, 2017, at 11:47 AM, Mike Ferenduros via swift-users 
>  wrote:
> 
> I'm doing a RAII sort of thing with an object, and would like to keep it 
> alive until an completion-block is called (asynchronously).
> 
> Is it sufficient to say '_ = x' in the completion-block to keep a live 
> reference to the object?
> 
> I was told that the optimiser is free to discard this line, and thus the 
> object could be freed prematurely depending on how the code is compiled. 
> If so, is there an idiomatic way to do this? Or should I just avoid RAII 
> in Swift?
 
 `withExtendedLifetime(x) { ... }` is the supported way of extending the 
 lifetime of an object.
 
 -Joe
>> 

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


Re: [swift-users] Is '_ = x' guaranteed to hold a reference to x?

2017-06-30 Thread Joe Groff via swift-users

> On Jun 30, 2017, at 12:13 PM, Mike Ferenduros  
> wrote:
> 
> With an empty body, you mean?

I'd say it's probably more readable to nest the code that's dependent on the 
lifetime of the object in the block body, though you can just put 
`withExtendedLifetime(x) { }` at the end of the region (or `defer { 
withExtendedLifetime... }` at the beginning) if you can't have the nesting for 
whatever reason.

-Joe

>> On 30 Jun 2017, at 22:00, Joe Groff  wrote:
>> 
>> 
>>> On Jun 30, 2017, at 11:47 AM, Mike Ferenduros via swift-users 
>>>  wrote:
>>> 
>>> I'm doing a RAII sort of thing with an object, and would like to keep it 
>>> alive until an completion-block is called (asynchronously).
>>> 
>>> Is it sufficient to say '_ = x' in the completion-block to keep a live 
>>> reference to the object?
>>> 
>>> I was told that the optimiser is free to discard this line, and thus the 
>>> object could be freed prematurely depending on how the code is compiled. If 
>>> so, is there an idiomatic way to do this? Or should I just avoid RAII in 
>>> Swift?
>> 
>> `withExtendedLifetime(x) { ... }` is the supported way of extending the 
>> lifetime of an object.
>> 
>> -Joe

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


Re: [swift-users] Swift alternative for heterogeneous collection of objects with "generic" contents.

2017-06-30 Thread Joe Groff via swift-users

> On Jun 29, 2017, at 10:59 PM, Mikhail Seriukov via swift-users 
>  wrote:
> 
> Hello everyone,
> In objc there is quite common pattern when we use a base class with a type 
> property and concrete subclasses where type is uniquely identifying the 
> subclass.
> We can then safely put subclasses objects into an array and then safely 
> downcast them when needed. 
> This kind of behaviour is commonly used in data sources implementations.
> 
> Like this:
> 
> typedef NS_ENUM(NSUInteger, CellDecriptorType) {
> CellDecriptorTypeUnknown,
> CellDecriptorType1,
> CellDecriptorType2
> };
> 
> @interface BaseCellDescriptor : NSObject
> 
> @property (nonatomic, readonly) CellDecriptorType type;
> @property (nonatomic, strong) id value;
> 
> @end
> 
> 
> @interface CellDescriptor1 : BaseCellDescriptor
> @end
> 
> @implementation CellDescriptor1
> 
> - (CellDecriptorType)type {
> return CellDecriptorType1;
> }
> 
> - (NSString *)value {
>   return @"string value";
> }
> 
> @end
> 
> 
> @interface CellDescriptor2 : BaseCellDescriptor
> @end
> 
> @implementation CellDescriptor2
> 
> - (CellDecriptorType)type {
> return CellDecriptorType2;
> }
> 
> - (NSNumber *)value {
>   return @42;
> }
> 
> @end
> 
> And somewhere later we do:
> 
> - (void)doWorkWithCellDescriptors:(NSArray 
> *)descriptors {
> for (BaseCellDescriptor *descriptor in descriptors) {
> CellDecriptorType type = descriptor.type;
> switch(type) {
> case CellDecriptorType1: {
> CellDescriptor1 *aDescriptor = (CellDescriptor1 *)descriptor;
> NSString *value = aDescriptor.value;
> // Do something with value
> break;
> }
> case CellDecriptorType2: {
> CellDescriptor2 *aDescriptor = (CellDescriptor2 *)descriptor;
> NSNumber *value = aDescriptor.value;
> // Do something with value
> break;
> }
> case CellDecriptorTypeUnknown:
> default: {
> // Handle error
> break;
> }
> }
> }
> } 
> 
> 
> I want to implement it swifty way. So the questions are:
> 0. Is it a bad practice to use this pattern and how we can avoid it?
> 1. Is it possible to avoid inheritance here and only use generic protocols 
> and how?
> 2. Is it possible to avoid downcasting if using this pattern in swift?
> 
> 
> I've found the solution that seems to be a good example in this project 
> https://github.com/xmartlabs/Eureka.
> They maintain both inheritance hierarchy and protocol hierarchy.

If you have a fixed set of types here, and you want to switch over them in a 
type-safe way, the natural thing to do would be to use an enum with payloads:

enum BaseCellDescriptor {
  case type1(CellDescriptor1)
  case type2(CellDescriptor2)
}

func doWorkWithCellDescriptors(_ descriptors: [BaseCellDescriptor]) {
  for descriptor in descriptors {
switch descriptor {
case .type1(let aDescriptor):
  // aDescriptor has type CellDescriptor1 here
case .type2(let aDescriptor):
  // aDescriptor has type CellDescriptor2 here
}
  }
}

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


Re: [swift-users] intercept fatalError() or other termination messages from swift?

2017-06-28 Thread Joe Groff via swift-users

> On Jun 26, 2017, at 7:45 PM, David Baraff  wrote:
> 
> Ok, the data is for sure not there, or possibly i’m looking at the wrong 
> thing. Here is what I see:
> 
> Incident Identifier: 15D12BCE-975B-47B6-BD03-DD8512D40DAF
> CrashReporter Key:   8af1402ae87b0184acff113b3f7312743d94d074
> Hardware Model:  iPad6,7
> Process: hackyApp [4965]
> Path:
> /private/var/containers/Bundle/Application/29195F7D-7548-4917-93D8-2B027481EAFB/hackyApp.app/hackyApp
> Identifier:  deb.hackyApp
> Version: 1 (1.1)
> Code Type:   ARM-64 (Native)
> Role:Foreground
> Parent Process:  launchd [1]
> Coalition:   deb.hackyApp [5747]
> 
> 
> Date/Time:   2017-06-26 19:38:48.2905 -0700
> Launch Time: 2017-06-26 19:38:48.1510 -0700
> OS Version:  iPhone OS 10.3.2 (14F89)
> Report Version:  104
> 
> Exception Type:  EXC_BREAKPOINT (SIGTRAP)
> Exception Codes: 0x0001, 0x00010045f734
> Termination Signal: Trace/BPT trap: 5
> Termination Reason: Namespace SIGNAL, Code 0x5
> Terminating Process: exc handler [0]
> Triggered by Thread:  0
> 
> Filtered syslog:
> None found
> 
> Thread 0 name:  Dispatch queue: com.apple.main-thread
> Thread 0 Crashed:
> 0   libswiftCore.dylib0x00010045f734 0x100304000 + 1423156
> 1   libswiftCore.dylib0x00010045f734 0x100304000 + 1423156
> 2   hackyApp  0x0001000b0708 0x1000a8000 + 34568
> 3   hackyApp  0x0001000b08c0 0x1000a8000 + 35008
> 4   UIKit 0x00019822cec0 -[UIViewController 
> loadViewIfRequired] + 1036
> 
> 
> …
> 
> The stack trace continues for a while, then a list of binary images.  There 
> is nothing that says "Application Specific Information”. Am I pulling the 
> wrong data in xcode?  Is my app setup in a weird way that this is not 
> reported?
> 
> This is doing the very simple “fatalError()” route in the main controller's 
> viewDidLoad() routine.
> 
> Thanks for any insights.

Unfortunately, it looks like iOS on-device prunes the application-specific info 
from crash logs because of user privacy concerns. The crash reason does show up 
in macOS or simulator crash logs, however.

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


Re: [swift-users] intercept fatalError() or other termination messages from swift?

2017-06-26 Thread Joe Groff via swift-users

> On Jun 26, 2017, at 12:22 PM, David Baraff  wrote:
> 
> To be very clear, i’m concerned about iOS not mac os x.  I pulled up a crash 
> report using xcode tools, and saw no mention of the string output by fatal 
> error.  If there is someway after the fact of, on an iPhone or iOS 
> interogating the asl_log when you restart your program to glean the error 
> message, i’m all ears.

The fatal error message ought to appear under the "Application Specific 
Information:" heading in the crash report Xcode pulls from the device.

-Joe

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


Re: [swift-users] Extracting arbitrary types (e.g. UInt16) out of Data

2017-06-26 Thread Joe Groff via swift-users

> On Jun 26, 2017, at 10:05 AM, Philippe Hausler  wrote:
> 
> Data.copyBytes will do that under the hood
> 
> var crc: UInt16 = 0
> let amountCopied = withUnsafeMutablePointer(to: ) { data.copyBytes(to: 
> UnsafeMutableBufferPointer(start: $0, count: 1)) }
> if amountCopied == MemoryLayout.size {
>// we have a full crc
> }
> 
> That will probably do what you want; plus it will allow you to do it from a 
> given range of bytes.

Cool. That'd be a nice API to backport to *BufferPointer too!

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


Re: [swift-users] Extracting arbitrary types (e.g. UInt16) out of Data

2017-06-26 Thread Joe Groff via swift-users

> On Jun 26, 2017, at 10:20 AM, Charles Srstka via swift-users 
>  wrote:
> 
> Rats, I was hoping that one of the reasons about being so explicit what we’re 
> going to access and where with bindMemory() and friends would be to take care 
> of these sorts of issues.

There are restrictions that unfortunately prevent unaligned memory support from 
being the pervasive default; particularly, we want typed pointers to be able to 
"toll-free-bridge" with typed C pointers, and C also requires well-alignedness 
of typed memory accesses. Swift's runtime generics model also means that 
unspecialized code would be using value witness functions to load/store values 
from memory, and the value witness functions are compiled to assume alignment 
of their arguments. It would be reasonable for us to add load/storeUnaligned 
APIs to the RawPointer types that explicitly did unaligned operations; these 
would however have to be restricted to working only on trivial types that don't 
require reference counting.

-Joe

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


Re: [swift-users] Swift 4 thread sanitizer more sensitive?

2017-06-26 Thread Joe Groff via swift-users

> On Jun 26, 2017, at 10:33 AM, Joe Groff via swift-users 
> <swift-users@swift.org> wrote:
> 
> 
>> On Jun 25, 2017, at 3:56 PM, Jon Shier via swift-users 
>> <swift-users@swift.org> wrote:
>> 
>>  Running Alamofire through the thread sanitizer and the thread sanitizer 
>> finds issues in Swift 4 mode but not Swift 3.2. Does Swift 4 add additional 
>> threading instrumentation that you don’t get under other versions? Or is 
>> there some other runtime difference that explains it?
> 
> Would you be able to file bugs for specific issues so we can investigate 
> whether the behavior changes are intentional?

cc'ing Anna, Devin, and Kuba who worked on improving TSan support for Swift.

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


Re: [swift-users] Swift 4 thread sanitizer more sensitive?

2017-06-26 Thread Joe Groff via swift-users

> On Jun 25, 2017, at 3:56 PM, Jon Shier via swift-users 
>  wrote:
> 
>   Running Alamofire through the thread sanitizer and the thread sanitizer 
> finds issues in Swift 4 mode but not Swift 3.2. Does Swift 4 add additional 
> threading instrumentation that you don’t get under other versions? Or is 
> there some other runtime difference that explains it?

Would you be able to file bugs for specific issues so we can investigate 
whether the behavior changes are intentional?

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


Re: [swift-users] intercept fatalError() or other termination messages from swift?

2017-06-26 Thread Joe Groff via swift-users

> On Jun 23, 2017, at 9:13 PM, David Baraff via swift-users 
>  wrote:
> 
> I realize this is slightly centric to iOS, but it irks me that both Apple’s 
> crash report logs and popular platforms like PLCrashReporter can do the hard 
> stuff like give you a stack trace, but are *completely* unable to display the 
> error message from terminating a program via fatalError(), or the error 
> message from, e.g. dying with a bad optional.
> 
> Is there *any* to intercept the error messages that from fatalError() and 
> similar like things in swift (bad optionals, invalid array accesses, 
> assertions)?  I would think that some sort of a “hook” into these standard 
> error routines would be a good thing.
> 
> In my case, if I could simply save that darn error string in a file, i could 
> pick it up when the app next launches and report it along with the rest of 
> the info like the stack/signal, etc.
> 
> I’ve been looking through the code in stdlib/public/runtime/Errors.cpp but 
> haven’t found anything promising that lets me jump in there.  In my code, I’m 
> likely to write things like
>   guard let x = … else {
>   fatalError(“Data type has payload  but is hooked to UI 
> control with intrinsic type ”)
>   }
> 
> and having that exact string tells me precisely what’s going, far simpler 
> than a stack trace.


Fatal error messages already get logged three ways:

- Printed to the process's stderr;
- Logged to the system log using asl_log;
- Set as the crash reason for CrashReporter.

The crash messages should thus already be in your crash reports somewhere. See 
https://github.com/jckarter/swift/blob/master/stdlib/public/runtime/Errors.cpp#L168
 

 and 
https://github.com/jckarter/swift/blob/master/stdlib/public/runtime/Errors.cpp#L204
 

 for the relevant runtime source code. cc'ing Greg Parker who probably knows 
better exactly where these messages end up.

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


Re: [swift-users] Extracting arbitrary types (e.g. UInt16) out of Data

2017-06-26 Thread Joe Groff via swift-users

> On Jun 26, 2017, at 1:55 AM, Daniel Vollmer via swift-users 
>  wrote:
> 
> Hi Rick,
> 
>> On 26. Jun 2017, at 02:37, Rick Mann via swift-users  
>> wrote:
> 
> [snip]
> 
>> I'd also like to avoid unnecessary copying of the data. All of it is 
>> immutable for the purposes of this problem.
>> 
>> How can I get the UInt16 that starts at byte X in a Data? Same goes for 
>> Double or Int32 or whatever.
> 
> I’m not sure what Swift’s stance on this is, but not all platforms allow 
> misaligned memory accesses (such as your attempt to access a UInt16 that lies 
> at an odd memory address).

Unaligned memory accesses are not currently allowed by the language semantics, 
regardless of the underlying ISA. You should use memcpy if you need to load 
potentially-unaligned values out of raw memory.

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


Re: [swift-users] Unimplemented types in Swift 4 KeyPaths

2017-06-21 Thread Joe Groff via swift-users

> On Jun 19, 2017, at 5:23 PM, Brett Walker via swift-users 
>  wrote:
> 
> Hi all,
> 
> In the Swift 4 Keypaths proposal [0161] there seem to be several types that 
> are unimplemented (or not working as I expect them to), and I'm not sure 
> whether these are simply unfinished in Beta 1, or just ideas that weren't 
> accepted.
> 
> For instance, according to the proposal AnyKeyPath is supposed to be fully 
> type-erased and access properties as optionals at run-time, but using it I 
> only get the compile-time error "Type "FooClass" has no subscript members", 
> even when applied to objects that still have the original type of the 
> KeyPath's root.
> 
> Even if I use PartialKeyPath I get the same error:
> --
> var tester = TestClass(name: "steve")
> let tester_path = \TestClass.name
> 
> let partial_path:PartialKeyPath = tester_path
> let name = tester[keyPath: partial_path] /// no subscript members error here
> --
> 
> Only when I either use the original path variable, or cast it to 
> KeyPath, am I able to access the property without an 
> error. I am wanting to use KeyPaths in a more generic way, so the AnyKeyPath 
> and PartialKeyPath would be helpful. Does anyone have insight into the status 
> of these KeyPath types?

Support for these did not make it into Xcode 9 beta 1. They are available in 
swift.org snapshot toolchains, if you want to experiment with them now, and 
should be in a future seed of Xcode 9.

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


Re: [swift-users] Help! Slicing an array is very expensive

2017-05-10 Thread Joe Groff via swift-users

> On May 8, 2017, at 4:47 PM, Rick Mann via swift-users  
> wrote:
> 
> I have this C library that interacts with some hardware over the network that 
> produces a ton of data. It tells me up front the maximum size the data might 
> be so I can allocate a buffer for it, then does a bunch of network requests 
> downloading that data into the buffer, then tells me when it's done and what 
> the final, smaller size is.
> 
> Thanks to previous discussions on the list, I settled on using a [UInt8] as 
> the buffer, because it let me avoid various .withUnsafePointer{} calls (I 
> need the unsafe buffer pointer to live outside the scope of the closures). 
> Unfortunately, When I go to shrink the buffer to its final size with:
> 
>self.dataBuffer = Array(self.dataBuffer![0 ..< finalBufferSize])
> 
> This ends up taking over 2 minutes to complete (on an iPad Pro). 
> finalBufferSize is very large, 240 MB, but I think it's doing a very naive 
> copy.
> 
> I've since worked around this problem, but is there any way to improve on 
> this?

`self.dataBuffer!.removeSubrange(finalBufferSize ..< 
self.dataBuffer!.endIndex)` might be more efficient. However, copying an array 
of bytes definitely shouldn't be that slow, so is worth a bug report.

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


Re: [swift-users] Atomics and Memory Fences in Swift

2017-05-01 Thread Joe Groff via swift-users

> On Apr 25, 2017, at 1:08 PM, Shawn Erickson <shaw...@gmail.com> wrote:
> 
> 
> On Mon, Dec 5, 2016 at 9:28 AM Joe Groff via swift-users 
> <swift-users@swift.org> wrote:
> 
>> On Dec 4, 2016, at 4:53 PM, Andrew Trick via swift-users 
>> <swift-users@swift.org> wrote:
>> 
>> 
>>> On Nov 30, 2016, at 5:40 AM, Anders Ha via swift-users 
>>> <swift-users@swift.org> wrote:
>>> 
>>> Hi guys
>>> 
>>> I have recently started adopting lock-free atomics with memory fences, but 
>>> it seems Swift at this moment does not have any native instruments.
>>> 
>>> Then I read a thread in the Apple Developer Forum 
>>> (https://forums.developer.apple.com/thread/49334), which an Apple staff 
>>> claimed that all imported atomic operations are "not guaranteed to be 
>>> atomic". But for my tests with all optimizations enabled (-Owholemodule and 
>>> -O), the OSAtomic primitives and stdatomic fences do not seem going wild.
>>> 
>>> Is these `atomic_*` and `OSAtomic*` primitives really unsafe in Swift as 
>>> claimed? It doesn't seem like the Swift compiler would reorder memory 
>>> accesses around a C function call that it wouldn't be able to see through.
>> 
>> Did you get an answer to this? I’m not sure what led you to believe the 
>> primitives are unsafe in Swift. Importing them doesn’t change their 
>> semantics.
> 
> If you apply them to memory you allocated manually with malloc/free on 
> UnsafeMutablePointer's allocation methods, then yeah, they should work as 
> they do in C. That's the safest way to use these functions today. Passing a 
> Swift `var` inout to one of these functions does not guarantee that accesses 
> to that var will maintain atomicity, since there may be bridging or 
> reabstracting conversions happening under the hood.
> 
> -Joe
> 
> Is the following in the ball park of being correct (going back over some old 
> code we have)...
> 
> public struct AtomicBool {
> 
> private static let bitLocation: UInt32 = 0
> private static let trueValue: UInt8 = 0x80
> private static let falseValue: UInt8 = 0x00
> 
> private let value = UnsafeMutablePointer.allocate(capacity: 1) // 
> TODO - leaking right? How to deal with that in a struct situation...?
> public var onSet: ((_ old: Bool, _ new: Bool) -> ())?
> 
> public init(_ intialValue: Bool = false) {
> value.initialize(to: intialValue ? AtomicBool.trueValue : 
> AtomicBool.falseValue)
> onSet = nil
> }
> 
> public init(_ intialValue: Bool = false, onSet: ((_ old: Bool, _ new: 
> Bool) -> ())?) {
> value.initialize(to: intialValue ? AtomicBool.trueValue : 
> AtomicBool.falseValue)
> self.onSet = onSet
> }
> 
> public mutating func set(_ newValue: Bool) {
> _ = getAndSet(newValue)
> }
> 
> public mutating func getAndSet(_ newValue: Bool) -> Bool {
> let oldValue: Bool
> if newValue {
> oldValue = 
> Darwin.OSAtomicTestAndSetBarrier(AtomicBool.bitLocation, value)
> }
> else {
> oldValue = 
> Darwin.OSAtomicTestAndClearBarrier(AtomicBool.bitLocation, value)
> }
> 
> onSet?(oldValue, newValue)
> return oldValue
> }
> 
> public func get() -> Bool { // TODO - document the lazy "safety" aspect 
> of get
> return value.pointee != AtomicBool.falseValue
> }

That looks OK. It might be better to provide an allocate/deallocate or with { 
... } interface instead of burying the allocate call in the initializer since 
the user will need to handle the deallocation of the buffer at some point.

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


Re: [swift-users] Cannot subclass a class with objc_subclassing_restricted attribute

2017-04-18 Thread Joe Groff via swift-users

> On Apr 17, 2017, at 10:11 PM, Rick Mann  wrote:
> 
>> 
>> On Apr 17, 2017, at 08:54 , Joe Groff  wrote:
>> 
>> 
>>> On Apr 14, 2017, at 7:41 PM, Rick Mann via swift-users 
>>>  wrote:
>>> 
>>> I'm refactoring some Objective-C code to inherit from a new Swift super 
>>> class. This has been going okay, and I've been cleaning up build errors as 
>>> I spot them (some auxiliary enums caused enum name changes, etc.).
>>> 
>>> But my last error seems to be that I can't subclass the Swift class: 
>>> "Cannot subclass a class with objc_subclassing_restricted attribute". I 
>>> didn't notice it before, and all the online references that say you can't 
>>> subclass a Swift class point to a Swift document that no longer mentions 
>>> that. They also don't say what they mean by "Swift" class (e.g. is it not 
>>> marked with @objc?).
>>> 
>>> In any case, my Swift class looks like:
>>> 
>>> @objc
>>> class
>>> Camera : NSObject
>>> {
>>>  ...
>>> }
>>> 
>>> And my ObjC class looks like:
>>> 
>>> @interface
>>> MCPCamera : Camera
>>> 
>>>  ...
>>> 
>>> @end
>>> 
>>> I feel like this is a reasonable thing to try to do. Is it just not 
>>> possible?
>> 
>> Subclassing Swift classes from Objective-C is not supported. If the 
>> documentation no longer mentions that restriction, we should fix that. Where 
>> is that document that you're referring to?
> 
> This is one document that doesn't clearly state it:
> 
>   
> https://developer.apple.com/library/content/documentation/Swift/Conceptual/BuildingCocoaApps/MixandMatch.html#//apple_ref/doc/uid/TP40014216-CH10-ID136
> 
> It has nice sections like "Using Swift from Objective-C," and "Declaring a 
> Swift Protocol That Can Be Adopted by an Objective-C Class," and "Adopting a 
> Swift Protocol in an Objective-C Implementation," but no "Inheriting a Swift 
> Class in Objective-C" (the discussion in such a section should explain that 
> it can't be done and why). Searching the document for "derive", "inherit", 
> "subclass" doesn't turn up any indication this can't be done.
> 
> Given that you can do all the other things, and there's such a thing as 
> marking a Swift class as @objc, and you can subclass in Swift, it's quite 
> unintuitive that you cannot go the other way.

Thanks. I'll file a bug with our documentation team to try to clarify that.

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


Re: [swift-users] Importing empty C structs

2017-04-18 Thread Joe Groff via swift-users

> On Apr 17, 2017, at 6:19 PM, Rick Mann via swift-users 
>  wrote:
> 
> I'm trying to make a module out of a C library and header file. It has at 
> least one empty struct:
> 
> struct lgs_context_t {};
> 
> and a function:
> 
> LGS_EXPORT struct lgs_context_t* lgs_init(const lgs_context_params_t* params);
> 
> Swift sees the function, I can call it and assign the result to a variable, 
> but Xcode (as usual) fails to show me what it thinks the type is. So I can't 
> declare a class member to hold the returned pointer.
> 
> I'm trying to declare the member like this:
> 
>varctx: lgs_context_t? //  Use of undeclared type 
> 'lgs_context_t'
> 
> I finally tried calling it like this:
> 
>let ctx: UnsafeMutablePointer = lgs_init(...)
> 
> and the resulting error message gave me OpaquePointer. But couldn't it just 
> typealias lgs_context_t to OpaquePointer?
> 
> Is there any way to do this in the modulemap?
> 
> Thanks!

The compiler uses OpaquePointer for pointers to incomplete types in C. It 
sounds like you left lgs_context_t declared but not defined in your header, in 
other words you wrote 'struct lgs_context_t;' without braces. If it were truly 
defined to be empty, then the type should have been imported.

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


Re: [swift-users] Cannot subclass a class with objc_subclassing_restricted attribute

2017-04-17 Thread Joe Groff via swift-users

> On Apr 14, 2017, at 7:41 PM, Rick Mann via swift-users 
>  wrote:
> 
> I'm refactoring some Objective-C code to inherit from a new Swift super 
> class. This has been going okay, and I've been cleaning up build errors as I 
> spot them (some auxiliary enums caused enum name changes, etc.).
> 
> But my last error seems to be that I can't subclass the Swift class: "Cannot 
> subclass a class with objc_subclassing_restricted attribute". I didn't notice 
> it before, and all the online references that say you can't subclass a Swift 
> class point to a Swift document that no longer mentions that. They also don't 
> say what they mean by "Swift" class (e.g. is it not marked with @objc?).
> 
> In any case, my Swift class looks like:
> 
> @objc
> class
> Camera : NSObject
> {
>...
> }
> 
> And my ObjC class looks like:
> 
> @interface
> MCPCamera : Camera
> 
>...
> 
> @end
> 
> I feel like this is a reasonable thing to try to do. Is it just not possible?

Subclassing Swift classes from Objective-C is not supported. If the 
documentation no longer mentions that restriction, we should fix that. Where is 
that document that you're referring to?

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


Re: [swift-users] Swift can’t compile code with OpenGL function pointers

2017-03-30 Thread Joe Groff via swift-users

> On Mar 30, 2017, at 9:40 AM, Kelvin Ma  wrote:
> 
> There are hundreds of gl functions… I have to rewrite the signatures for all 
> of them??

Does GLFW expose any underlying loader mechanism or cached function pointer 
variables underneath the macros it defines? Possibly you could access those 
directly. Otherwise, code generation might be your best bet. You should be able 
to get types like GLenum or GLint just by importing them normally, since those 
are purely compile-time constructs.

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


Re: [swift-users] Swift can’t compile code with OpenGL function pointers

2017-03-30 Thread Joe Groff via swift-users

> On Mar 30, 2017, at 7:47 AM, Kelvin Ma via swift-users 
>  wrote:
> 
> OpenGL functions are loaded at runtime by a function loader (like GLFW). 
> They’re defined in a header but obviously they don’t have definitions at 
> compile time so it causes a slew of linker errors when I try to build
> 
> error: undefined reference to 'glEnable'
> error: undefined reference to 'glBlendFunc'
> error: undefined reference to 'glClearColor'
> clang: error: linker command failed with exit code 1 (use -v to see 
> invocation)
> ...
> 
> How do I build programs that use OpenGL functions?

If the functions are exported by the OpenGL library you're linking against, 
then you may need to just use -lGL to link against it. That's not likely to be 
portable, though, since implementations vary in what they statically export. 
The macro metaprogramming used by GLFW and other libraries to dynamically load 
GL entry points is probably not going to get picked up by Swift's C importer, 
so you'd need to roll your own solution. Something like this might work as a 
start:

func loadGLFunction(name: String) -> T {
#if os(macOS)
  return unsafeBitCast(dlsym(RTLD_DEFAULT, name), to: T.self)
#elseif os(Linux)
  return unsafeBitCast(glXGetProcAddress(name), to: T.self)
#elseif os(Windows)
  return unsafeBitCast(wglGetProcAddress(name), to: T.self)
#endif
}

enum GL {
  static let begin: @convention(c) (GLenum) -> Void = loadGLFunction("glBegin")
  static let end: @convention(c) () -> Void = loadGLFunction("glEnd")
  /*etc*/
}

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


Re: [swift-users] Set with element of NSObject subclasses didn't work as expected

2017-03-29 Thread Joe Groff via swift-users

> On Mar 28, 2017, at 12:50 PM, Zhao Xin via swift-users 
>  wrote:
> 
> Please see the code first.
> 
> import Foundation
> 
> class Foo:Hashable {
> let value:Int
> 
> public var hashValue: Int { return value }
> public static func ==(lhs: Foo, rhs: Foo) -> Bool {
> return lhs.value == rhs.value
> }
> 
> init(_ value:Int) {
> self.value = value
> }
> }
> 
> let fooSetA:Set = [Foo(8), Foo(9)]
> let fooSetB:Set = [Foo(9), Foo(10)]
> let fooResultC = fooSetA.intersection(fooSetB) // {{value 9}}
> let fooResultD = fooSetA.subtracting(fooSetB) // {{value 8}}
> 
> 
> class Bar:NSObject {
> let value:Int
> 
> override public var hashValue: Int { return value }
> public static func ==(lhs: Bar, rhs: Bar) -> Bool {
> return lhs.value == rhs.value
> }
> 
> init(_ value:Int) {
> self.value = value
> }
> }
> 
> let barSetA:Set = [Bar(8), Bar(9)]
> let barSetB:Set = [Bar(9), Bar(10)]
> let barResultC = barSetA.intersection(barSetB) // Set([])
> let barResultD = barSetA.subtracting(barSetB) // {{NSObject, value 9}, 
> {NSObject, value 8}}
> 
> 
> Behaviors of `func intersection(Set)` and `func 
> subtracting(Set)` were different between normal Swift class and 
> NSObject subclasses. I had thought they should be the same. It seemed that 
> Set relied on addresses of NSObject instances instead of their 
> hashValues. That made the Set useless.

This is a known issue—when you redeclare `static func ==` inside Bar, that does 
not override `NSObject.==`, and moreover *cannot*, since overriding 
`NSObject.==` requires an implementation that accepts two NSObjects. We ought 
to consider this an error, or at least a warning. NSObject conforms to 
Equatable on behalf of all its subclasses by implementing `==` in terms of 
`isEqual:` and `hashValue` in terms of `hash`. Even though you can override 
`hashValue` for Swift, it's probably still safer to override `hash` and 
`isEqual` in order to get common behavior between ObjC and Swift, since ObjC 
will not use Swift's conformances. Perhaps the NSObject implementation of 
`hashValue` should be final to help with this.

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


Re: [swift-users] Memory Leak of Dictionary used in singleton

2017-03-24 Thread Joe Groff via swift-users

> On Mar 11, 2017, at 4:04 PM, Ekaterina Belinskaya via swift-users 
>  wrote:
> 
> Hi everyone!
> 
> I have singleton. It contains a 2 dictionaries. 
> 
> struct Stat {
> var statHash:String
> var displayDescription:String
> var displayName:String
> var displayIcon:String
> var statIdentifier:String
> }
> 
> class Singleton {
> 
> static let sharedInstance = Singleton()
> 
> var statsDesc = [String:Stat]()
> var test = [String: String]()
> 
> init() {
> test["a"] = "b"
> }
> }
> 
> let singlton = Singleton.sharedInstance
> On using the leaks tool, I am getting a memory leak of the second 
> dictionary(String, String).
> 
> screenshot of memory graph debugger 
> 
> If i remove dictionaries and write smth like that:
> 
> class Singleton {
> 
> static let sharedInstance = Singleton()
> var num: Int
> 
> init() {
> num = 3
> }
> }
> leak disappears.
> 
> Could someone, please, explain why this happens?
> 
> 

This sounds a lot like:

https://bugs.swift.org/browse/SR-3661  
Memory Leak from Multiple Dictionary Properties

which was fixed in Xcode 8.3. What version of the compiler are you using?

-Joe

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


Re: [swift-users] Why does casting to Any make my forced downcast not crash?

2017-03-15 Thread Joe Groff via swift-users

> On Mar 15, 2017, at 4:47 AM, Kim Burgestrand  wrote:
> 
> On Tue, 14 Mar 2017 at 19:50 Joe Groff  > wrote:
> 
> It shouldn't. Please file a bug, if you haven't already.
> 
> Will do! I'll file a bug that casting to `Any` first causes different 
> behavior.
> 
> Follow-up question, looking at the expression `name as! T`, is it expected to 
> cause a nil-unwrapping runtime error when `name == nil` and `T == 
> Optional`? Mind you, `(nil as! Optional)` does not cause an 
> error.

If you're casting to an Optional destination type, then the cast ought to 
succeed and produce a `nil` result if the input is nil.

-Joe

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


Re: [swift-users] Why does casting to Any make my forced downcast not crash?

2017-03-14 Thread Joe Groff via swift-users

> On Mar 13, 2017, at 5:13 AM, Kim Burgestrand via swift-users 
>  wrote:
> 
> Here are two implementations that I'd expect to be equivalent, but 
> something's different because the first example crashes, whereas the second 
> example does not crash.
> 
> What's the difference between these two? Why does casting to Any before the 
> forced downcast to T have any effect?

It shouldn't. Please file a bug, if you haven't already.

-Joe

> Example 1: (`unexpectedly found nil while unwrapping an Optional value`)
> ```
> func cast(_ name: String?) -> T {
> return name as! T
> }
> 
> debugPrint((cast(nil) as String?) as Any))
> ```
> 
> Example 2: (prints `nil`)
> ```
> func cast(_ name: String?) -> T {
> return (name as Any) as! T
> }
> 
> 
> debugPrint((cast(nil) as String?) as 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] Swift/Obj C interoperability: 'Obj C only' functions

2017-03-07 Thread Joe Groff via swift-users

> On Mar 6, 2017, at 2:20 AM, Andrew Hill2 via swift-users 
>  wrote:
> 
> Hi,
> 
> I’ve been looking at making some changes to the ResearchKit library. This is 
> mainly written in Objective C, with small portions of Swift.
> 
> The Pull request I’ve generated leveraged Swift generics to make handling 
> predicates easier from Swift.
> 
> 
> The existing functions had to utilise different functions for each type of 
> object.
> 
> The Swift function of course uses generics and simplifies that down to a 
> single function.
> 
> To maintain Objective C compatibility, we still need to provide the original 
> functions for Obj C programmers. We don’t want to re-implement the functions 
> twice in two different ways, and we want Obj C programmers to use one set of 
> functions, and Swift programmers to only use the other one.
> 
> 
> It’s easy enough to expose a function from Swift to Objective C code of 
> course.
> 
> However, is there a way to expose a function in a Swift file which is ONLY 
> available externally to Objective C files and not to other Swift ones? (or at 
> least warns if called from Swift or something like that)? Basically an 
> @objconly ?
> 
> The case described above is fairly trivial, but there are more complicated 
> areas where this would have a more marked effect. It would be nice not to 
> have Swift ResearchKit developers exposed to a load of API functions they 
> don’t need which are there only to support Obj C.

The closest thing might be to declare the methods as `@objc private`. They 
won't be exported to Swift, but ObjC code can still get at the method by its 
selector if you declare it in your ObjC headers.

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


Re: [swift-users] question about covariant subtyping

2017-02-23 Thread Joe Groff via swift-users

> On Feb 23, 2017, at 4:45 AM, Michael Roitzsch  
> wrote:
> 
> So I understand that the first issue is a bug and the second may be a bug or 
> may be intentional. Would you advise that I file them both as bugs then?

They're both bugs, ultimately. Slava was just pointing out that the second may 
be due to implementation limitations rather than oversight; either way, we 
should ultimately remove the limitation.

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


Re: [swift-users] question about covariant subtyping

2017-02-22 Thread Joe Groff via swift-users

> On Feb 22, 2017, at 8:50 AM, Michael Roitzsch via swift-users 
>  wrote:
> 
> Hi all,
> 
> I am fairly new to Swift, so this may very well be a simple misunderstanding 
> on my part.
> 
> I was exploring the subtyping rules of Swift, especially regarding 
> covariance. I came across two examples where the outcome puzzles me and I 
> would appreciate if someone could explain this to me.
> 
> First I tried the covariance for the standard container types. Here is an 
> excerpt from a REPL session:
> 
> Michael@carpo:~ > swift
> Welcome to Apple Swift version 3.0.2 (swiftlang-800.0.63 clang-800.0.42.1). 
> Type :help for assistance.
>  1> open class Super {}; class Sub: Super {}
>  2> print([Sub()] is [Sub])
> true
>  3> print([Sub()] is [Super])
> true
>  4> print(Array(arrayLiteral: Sub()) is [Sub])
> true
>  5> print(Array(arrayLiteral: Sub()) is [Super])
> error: repl.swift:5:39: error: 'Super' is not a subtype of 'Sub'
> print(Array(arrayLiteral: Sub()) is [Super])
>  ^~
> 
> Why does it matter for subtyping against [Super] whether I express an array 
> as [Sub] or Array(arrayLiteral: Sub())?
> 
> Then I tried combining array covariance with function argument type 
> contravariance:
> 
> Michael@carpo:~ > swift
> Welcome to Apple Swift version 3.0.2 (swiftlang-800.0.63 clang-800.0.42.1). 
> Type :help for assistance.
>  1> open class Super {}; class Sub: Super {}
>  2> func f(_: [Super]) {}
>  3> let test: ([Sub]) -> Void = f
> error: repl.swift:3:29: error: cannot convert value of type '([Super]) -> ()' 
> to specified type '([Sub]) -> Void'
> let test: ([Sub]) -> Void = f
>^
> 
> Why is this assignment not possible? It works fine (as expected) when using 
> plain Super and Sub instead of arrays.

Those are both bugs. There's no fundamental reason these should be errors.

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


Re: [swift-users] Non-objc protocol inheritance from objc protocol

2017-02-06 Thread Joe Groff via swift-users

> On Feb 6, 2017, at 3:22 PM, Jordan Rose via swift-users 
>  wrote:
> 
> Hi, Pavel. This is definitely supported, and it is indeed a bug that these 
> are not both producing 'true'. We're tracking this as rdar://problem/24453316 
> .

I also filed this as https://bugs.swift.org/browse/SR-3882 
 since it seems like a reasonable IRGen 
starter bug too.

-Joe

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


Re: [swift-users] Avoiding an extra copy withUnsafeBytes

2017-01-26 Thread Joe Groff via swift-users

> On Jan 26, 2017, at 7:03 AM, Ray Fix via swift-users  
> wrote:
> 
> To compute a hash, I want to loop through bytes of a trivial type.  To get 
> the bytes, I use withUnsafeBytes hands me a rawBufferPointer collection type. 
>  Great!
> 
> However this call also requires that the "of arg" be declared as a “var" 
> instead of “let” because it is inout.  So to do it generically, it forces me 
> to make a copy to some var storage.  
> 
> Since I am using withUnsafeBytes and not withUnsafeMutableBytes, though, it 
> doesn’t seem like this copy should be necessary.  Is there some way to avoid 
> it?  Is it something the compiler should be able to reason about and 
> therefore elide? Possibly a future evolution (and something for that list)?
> 
> On a side note, wouldn’t it be cool if there where a way to enforce that a 
> type was trivial?
> 
> Then one could write code like:
> 
> func consume(value: T) {
>   var copy = value
>   withUnsafeMutableBytes(of: ) { rawBufferPointer in
> // something interesting
>   }
> }
> 
> Always appreciate the great insights I get here.
> Thanks as always. Best wishes,

There's no fundamental reason it needs a var; see 
https://bugs.swift.org/browse/SR-3679. The formal copy can often be elided by 
the LLVM optimizer in most cases, though unfortunately not all 
(https://llvm.org/bugs/show_bug.cgi?id=31697 is one such case). There is some 
benefit to encouraging people to use the `inout` version when possible in our 
current language, though in the fullness of time, the operand would be better 
modeled as an "immutable borrow" in the ownership model.

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


Re: [swift-users] Casting function pointers

2017-01-25 Thread Joe Groff via swift-users

> On Jan 25, 2017, at 1:23 AM, Rien via swift-users  
> wrote:
> 
> I have a case where a callback has the following signature:
> 
> @convention(c) (_ ssl: OpaquePointer?, _ num: UnsafeMutablePointer?, _ 
> arg: UnsafeMutableRawPointer?) -> Int32
> 
> But to install this callback I have to use a c-function with this signature:
> 
> SSL_CTX_callback_ctrl (OpaquePointer!, Int32, (() -> Void)! )
> 
> Is it possible to cast the first function to the second? If so, how?

I think your best bet would be to write the shim closure yourself. Is `num` a 
pointer to the value you're supposed to receive from SSL_CTX_callback_ctrl? Is 
the `arg` really a function pointer? In that case, something like this might 
work:

func callback(_ ssl: OpaquePointer?, _ num: UnsafeMutablePointer?, _ 
arg: UnsafeMutableRawPointer?) -> Int32

let shimCallback: SSL_CTX_callback_ctrl = { ctx, cmd, fp in
  var cmdNum = cmd
  callback(ctx, , unsafeBitCast(fp, to: UnsafeMutableRawPointer?.self))
}

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


Re: [swift-users] Bool type and reading and writing operation atomicity

2017-01-17 Thread Joe Groff via swift-users

> On Jan 16, 2017, at 3:27 AM, Dale Myers via swift-users 
>  wrote:
> 
> Put simply, are reading and writing to Bools both atomic operations in Swift 
> (3)?
> 
> Obviously, something reading and then assigning assuming the value doesn't 
> change between is not correct, but would something like the following be 
> fine: 
> 
>var myBool = false
> 
>// Thread 1
>while true {
>if randomEvent() {
>myBool = true
>}
>}
> 
>// Thread 2
>while true {
>if myBool {
>print("Was set to true")
>} else {
>print("Not set")
>}
>}
> 
> 
> I understand that in thread 2, the value of myBool can change between the 
> check and the print statements, but that's fine. What I want to confirm for 
> my team is that `myBool` can never be in some weird "third" state? 
> 
> From what I can tell, behind the scenes, Bool uses a Builtin.Int1 for 
> storage. I can't find the definition for this type anywhere so I can't check 
> what it is really doing. My assumption is that it uses something like a C++ 
> unsigned char behind the scenes, which would be fine with the above code on 
> x86 and ARM as far as I'm aware. 
> 
> Can someone help me figure out if I'm right or wrong in my assumptions?

Nothing in Swift is formally atomic. You'll need to use external APIs that 
provide atomic operations, such as OSAtomic* on Apple platforms, with raw 
memory if you need to do that sort of thing in Swift today.

If you naively ported this code to C or C++, it would also formally have a data 
race, since unless `myBool` is std::atomic (C++) or _Atomic (C11), the compiler 
will assume that `myBool` is not concurrently accessed and emit nonatomic 
loads/stores or optimize accordingly. When Swift does gain proper support for 
atomics, it will almost certainly be something you have to opt in to as well.

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


Re: [swift-users] Swift 3 Whole Module Optimization Issue

2016-12-21 Thread Joe Groff via swift-users

> On Dec 21, 2016, at 7:08 PM, Jun Zhang via swift-users 
>  wrote:
> 
> Hi, everyone.
>I think I found a swift 3 whole module optimization issue. The code below, 
> when building with release configuration and running on an iOS 10 real 
> device, will always causes a crash.
> 
> import UIKit
> class ViewController: UIViewController {
> override func viewDidLoad() {
> super.viewDidLoad()
> // Do any additional setup after loading the view.
> super.viewDidLoad()
> 
> let orderby = "time"
> let url = "http://www.sample.com/api/index.php?\(orderby)"
> 
> Log("Request url: \(url)")
> 
> if let url = URL(string: url) {
> let request = URLRequest(url: url)
> print(request)
> }
> }
> override func didReceiveMemoryWarning() {
> super.didReceiveMemoryWarning()
> // Dispose of any resources that can be recreated.
> }
> 
> }
> func Log(_ log: String) {
> //NSLog("%@", log)
> }
> 
> You can see the attachment for more detail info.
> Or if you use github, this is the repo: 
> https://github.com/zaczh/Swift3ClosureDemo​
>  Swift3ClosureDemo-master.zip
> ​
Thanks for the report! Please file it on bugs.swift.org if you have a moment.

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


Re: [swift-users] Bls: module (de)-initialization

2016-12-21 Thread Joe Groff via swift-users

> On Dec 21, 2016, at 7:11 PM, Mr Bee  wrote:
> 
> > Unloading Swift modules will likely never be supported, since this would 
> > impose a ton of complexity and performance cost on the runtime for little 
> > benefit.
> 
> Hmmm… so Swift will only support static linking? I thought Swift is a modern 
> programming language with modern and advance features. Even Pascal/Delphi has 
> had those features since ages ago.

Swift supports dynamic linking just fine; like I said, "dlopen" works.

-Joe

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


Re: [swift-users] Implicitly capture a mutating self

2016-12-16 Thread Joe Groff via swift-users

> On Dec 16, 2016, at 12:10 PM, Richard Wei  wrote:
> 
> `sync` is not escaping. Shadow copy causes the device memory to make a copy, 
> which can’t be a solution either. I’ll file a radar.
> 
>> Note that, independently, this part looks fishy:
>> 
>>> try! fill<<<(blockSize, blockCount)>>>[
>>>   .pointer(to: )
>> 
>> UnsafePointers formed by passing an argument inout are not valid after the 
>> called function returns, so if this function is forming and returning a 
>> pointer, it will likely result in undefined behavior. You should use 
>> `withUnsafePointer() { p in ... }` to get a usable pointer.
> 
> This part is a semi-"type safe” wrapper to CUDA kernel launcher. The purpose 
> is to make explicit which argument gets passed to the kernel as a pointer; in 
> this case, self is a `DeviceArray`. `.pointer` is a factory method under 
> `KernelArgument`. Since most arguments to the kernel are passed in by 
> pointers, IMO using a bunch of `withUnsafe...` clauses would only make it 
> look unnecessarily clumsy.

Unfortunately, that's the only defined way to write this code. The pointer you 
get as an argument from `` is only good until pointer(to:) returns, so it 
won't be guaranteed to be valid by the time you use it, and the compiler will 
assume that `self` doesn't change afterward, so any mutation done to `self` 
through that pointer will lead to undefined behavior. Rewriting this code to 
use withUnsafePointer should also work around the capture bug without requiring 
a shadow copy:

   let blockSize = min(512, count)
   let blockCount = (count+blockSize-1)/blockSize
   withUnsafePointer(to: ) { selfPtr in 
 device.sync { // Launch CUDA kernel
 try! fill<<<(blockSize, blockCount)>>>[
 .pointer(to: selfPtr), .value(value), .value(Int64(count))
 ]
 }
  }

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


Re: [swift-users] Implicitly capture a mutating self

2016-12-16 Thread Joe Groff via swift-users

> On Dec 15, 2016, at 11:46 PM, Richard Wei via swift-users 
>  wrote:
> 
> Hi,
> 
> Swift 3.0.2 seems to have broken my code due to mutating self capture. But I 
> have to pass inout self to the closure. Any workaround?
> 
> let blockSize = min(512, count)
> let blockCount = (count+blockSize-1)/blockSize
> device.sync { // Launch CUDA kernel
> try! fill<<<(blockSize, blockCount)>>>[
> .pointer(to: ), .value(value), .value(Int64(count))
> ]
> }

This looks like a compiler bug. Assuming `sync`'s closure is not @escaping, it 
should be allowed to capture self. If you haven't yet, would you be able to 
file a bug at bugs.swift.org? Does making a shadow copy work as a workaround, 
something like:

var tmpSelf = self
device.sync {...  ...}
self = tmpSelf

Note that, independently, this part looks fishy:

> try! fill<<<(blockSize, blockCount)>>>[
> .pointer(to: )

UnsafePointers formed by passing an argument inout are not valid after the 
called function returns, so if this function is forming and returning a 
pointer, it will likely result in undefined behavior. You should use 
`withUnsafePointer() { p in ... }` to get a usable pointer.

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


Re: [swift-users] Swift ported on FreeBSD platform

2016-12-08 Thread Joe Groff via swift-users

> On Dec 7, 2016, at 5:43 PM, Sid via swift-users  wrote:
> 
> Swift has been ported to FreeBSD. You can see that here 
> http://www.freshports.org/lang/swift .
>  
> Can https://swift.org/about/#platform-support be updated to reflect this? 
> Thank you.

It's great that people have contributed ports to other platforms. Declaring a 
platform as officially supported on swift.org, though, implies a bit more 
infrastructure on our part, such as CI to ensure the port remains working in 
active development, regular generation of nightly and/or release binaries, etc. 
We only have this infrastructure in place for Ubuntu and Apple platforms right 
now, and we're still working out ways for contributors to provide 
infrastructure to fully support additional platforms.

As a bit of advice, I'd recommend including the Swift version in the port name, 
to call it 'swift-2.2' or 'swift-3.0' or whatever, since Swift 2 and Swift 3 
are different source-level languages, and the Swift ABI is not yet settled, so 
any source- or binary-based packages that depend on Swift are going to 
necessarily depend on an exact compiler version for now.

-Joe

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


Re: [swift-users] ObjC vs Swift action selectors

2016-12-06 Thread Joe Groff via swift-users

> On Dec 6, 2016, at 12:53 PM, David Catmull  wrote:
> 
> I tried, writing that as @objc(action:) #selector(ClassName.action(_:)) but 
> that got an "expected declaration" error.
> 
> I also tried adding @objc(action:) to the method itself (which seems 
> redundant anyway), but that didn't help either.

The attribute has to go on the method definition. Would you be able to file a 
bug on bugs.swift.org  with your Swift and ObjC code?

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


Re: [swift-users] ObjC vs Swift action selectors

2016-12-06 Thread Joe Groff via swift-users

> On Dec 6, 2016, at 8:54 AM, David Catmull via swift-users 
>  wrote:
> 
> I have a unit test in which I verify that a view controller is correctly 
> validating items in a context menu. I converted the view controller class to 
> Swift, keeping the selector names the same, while the test is still in ObjC. 
> The test now doesn't work because the selector created in ObjC as 
> @selector(action:) somehow isn't matching Swift's 
> #selector(ClassName.action(_:)). Do I have to rewrite my test in Swift for 
> this to work?

You could try giving ClassName.action(_:) an explicit selector using the 
@objc(action:) attribute to ensure that it's consistent with the ObjC code. If 
that doesn't work, then we may have a bug in the compiler.

-Joe

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


Re: [swift-users] Atomics and Memory Fences in Swift

2016-12-05 Thread Joe Groff via swift-users

> On Dec 4, 2016, at 4:53 PM, Andrew Trick via swift-users 
>  wrote:
> 
> 
>> On Nov 30, 2016, at 5:40 AM, Anders Ha via swift-users 
>> > wrote:
>> 
>> Hi guys
>> 
>> I have recently started adopting lock-free atomics with memory fences, but 
>> it seems Swift at this moment does not have any native instruments.
>> 
>> Then I read a thread in the Apple Developer Forum 
>> (https://forums.developer.apple.com/thread/49334 
>> ), which an Apple staff 
>> claimed that all imported atomic operations are "not guaranteed to be 
>> atomic". But for my tests with all optimizations enabled (-Owholemodule and 
>> -O), the OSAtomic primitives and stdatomic fences do not seem going wild.
>> 
>> Is these `atomic_*` and `OSAtomic*` primitives really unsafe in Swift as 
>> claimed? It doesn't seem like the Swift compiler would reorder memory 
>> accesses around a C function call that it wouldn't be able to see through.
> 
> Did you get an answer to this? I’m not sure what led you to believe the 
> primitives are unsafe in Swift. Importing them doesn’t change their semantics.

If you apply them to memory you allocated manually with malloc/free on 
UnsafeMutablePointer's allocation methods, then yeah, they should work as they 
do in C. That's the safest way to use these functions today. Passing a Swift 
`var` inout to one of these functions does not guarantee that accesses to that 
var will maintain atomicity, since there may be bridging or reabstracting 
conversions happening under the hood.

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


Re: [swift-users] Indirectly calling functions through assembly

2016-11-28 Thread Joe Groff via swift-users

> On Nov 26, 2016, at 5:20 PM, Krishna Mannem via swift-users 
>  wrote:
> 
> I’ve been messing around with swift and trying to figure out the internals 
> for fun. I’ve been running into a seg fault while running this gist 
> (https://gist.github.com/krishnamannem/032aa7b568f82297ba2f88041518085d), the 
> seg fault happens in the print(). 
> 
> Going through the execution with lldb I know the error is inside print and 
> the only difference between the disassembled versions is some retain release 
> stuff which I don’t think is the issue. I have very little experience with 
> swift so you’ll have to excuse me if I’m totally screwing/mixing something 
> up. Does anyone know what extra magic testing(x: () -> ()) { x() }  does to 
> ensure it doesn’t segfault. 
> 
> Side note: I have replaced the print with a plain var _ = 1 + 1 and this 
> worked just fine.
> 
> I ran this using :
> 
> Llvm-g++ -c func.S -o func.o
> Swiftc -g func.swift func.o

It appears that something about the Swift source that built `using_asm.S` is 
making the Swift compiler try to call `testing` as if it were a C function. You 
can see in the disassembly there that it's emitting a `_TTo` thunk for `hello` 
that really shouldn't be necessary. It'd be worth filing a bug about this, 
since I don't see any reason why your assembly version wouldn't work in this 
specific case. In the more general case, where `_test` may be passed a closure 
with captures, your `_test` function would need to pass the closure parameter 
context through to the invocation function too, something like:

mov %rdi, %rax
mov %rsi, %rdi
call *%rax

though `hello` is a top-level function without captures, so this shouldn't 
matter in this case.

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


Re: [swift-users] Decimal to Double?

2016-11-28 Thread Joe Groff via swift-users

> On Nov 28, 2016, at 11:42 AM, Nevin Brackett-Rozinsky 
> <nevin.brackettrozin...@gmail.com> wrote:
> 
> On Mon, Nov 28, 2016 at 2:21 PM, Joe Groff via swift-users 
> <swift-users@swift.org> wrote:
> ExpressibleByFloatLiteral uses a binary float initial value and so doesn't 
> guarantee decimal accuracy
> 
> That seems like a flaw in ExpressibleByFloatLiteral that should be fixed.
> 
> Did anyone ever submit a proposal following the discussion in 
> “[swift-evolution] Allow FloatLiteralType in FloatLiteralConvertible to be 
> aliased to String” where somebody—*runs to check*…oh it was you!—described 
> the proper solution?

Fixing ExpressibleByFloatLiteral has come up several times, but nobody's 
formally written up the proposal AFAIK.

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


Re: [swift-users] Decimal to Double?

2016-11-28 Thread Joe Groff via swift-users

> On Nov 28, 2016, at 9:22 AM, Alex Blewitt via swift-users 
>  wrote:
> 
> NSDecimal conforms to the ExpressibleBy(Float|Integer)Literal, but that just 
> means it can be created from a literal value, not the other way around:
> 
> https://github.com/apple/swift-corelibs-foundation/blob/108a5b0006912c6cf6b59e4954255237bf01b67a/Foundation/NSDecimal.swift#L319-L329
> 
> 
> 
> extension Decimal : ExpressibleByFloatLiteral {
> public init(floatLiteral value: Double) {
> self.init(value)
> }
> }
> 
> extension Decimal : ExpressibleByIntegerLiteral {
> public init(integerLiteral value: Int) {
> self.init(value)
> }
> }

It really shouldn't be, since ExpressibleByFloatLiteral uses a binary float 
initial value and so doesn't guarantee decimal accuracy. I'd recommend using 
init(mantissa:exponent:isNegative:) instead, and minimizing any conversions 
between Double and Decimal.

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


Re: [swift-users] Understanding pass-by-value

2016-11-04 Thread Joe Groff via swift-users

> On Nov 4, 2016, at 10:12 AM, Rien via swift-users  
> wrote:
> 
> 
>> On 04 Nov 2016, at 17:48, Ryan Lovelett  wrote:
>> 
>>> I often end up “printing” the addresses or using GDB to take an inside
>>> look.
>> 
>> That is a really simple interrogation technique I wish I had thought of
>> that! Thank you!
>> 
>>> One thing that tripped me up: if you use inout variables, the observers
>>> will be triggered once the function completes. Even if the function never
>>> changed the data referred to. (This is now documented behaviour)
>> 
>> Could you provide a link to such documentation? I think that would be
>> interesting to read.
> 
> https://developer.apple.com/library/prerelease/content/documentation/Swift/Conceptual/Swift_Programming_Language/Properties.html#//apple_ref/doc/uid/TP40014097-CH14-ID254
> 
> Check the last ‘note’ in the Property Observer section.
> You can also follow the link in there for more.

There's also some deeper documentation about the accessor model in the 
compiler, here:

https://github.com/jckarter/swift/blob/master/docs/proposals/Accessors.rst 


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


Re: [swift-users] Autoreleasepool for Ubuntu

2016-11-02 Thread Joe Groff via swift-users

> On Nov 2, 2016, at 1:16 PM, Bernardo Breder via swift-users 
>  wrote:
> 
> In my http server i want to manager the memory all the time that we close a 
> socket, like the example of manager in this link: 
> http://stackoverflow.com/questions/25860942/is-it-necessary-to-use-autoreleasepool-in-a-swift-program
>  
> 
> 
> Algorithm that show the ideia:
> 
> func request(content) { ... }
> 
> let server = myserver()
> while let client = server.accept() {
>   autoreleasepool {
> client.send(request(client.read()))
> client.close()
>   }
> }

Is `client` really getting autoreleased somewhere? autoreleasepool shouldn't 
normally be necessary. The client will be released when you go out of scope.

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


Re: [swift-users] Autoreleasepool for Ubuntu

2016-11-02 Thread Joe Groff via swift-users

> On Nov 2, 2016, at 1:00 PM, Philippe Hausler  wrote:
> 
> See:
> 
> https://github.com/apple/swift-corelibs-foundation/blob/d015466450b2675037c6f1ace8e17e73050ccfb9/Foundation/NSURL.swift#L561
>  
> 
> 
> This is far and few between of cases that it would be useful but there are a 
> few APIs that we have not been able to express without being able to 
> autorelease items. Most of which we have either forbidden in Linux or 
> redesigned because they were sub-par swift experiences. However it seems 
> reasonable to have a minimal shim to provide cross platform code 
> compatibility even if it does next to nothing. That way trivial code as the 
> original issue showed can easily be directly compiled on either platform 
> without littering gnarly #ifdefs about.

In the fullness of time, the borrow model will hopefully give us a way to 
represent those kinds of "returns inner pointer" APIs safely in Swift without 
relying on dynamic lifetime extension, or awkward 'with { ... }' callbacks.

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


Re: [swift-users] Autoreleasepool for Ubuntu

2016-11-02 Thread Joe Groff via swift-users

> On Nov 2, 2016, at 10:17 AM, Jordan Rose <jordan_r...@apple.com> wrote:
> 
>> 
>> On Nov 2, 2016, at 09:42, Joe Groff via swift-users <swift-users@swift.org 
>> <mailto:swift-users@swift.org>> wrote:
>> 
>>> 
>>> On Nov 1, 2016, at 6:40 PM, Bernardo Breder via swift-users 
>>> <swift-users@swift.org <mailto:swift-users@swift.org>> wrote:
>>> 
>>> Hello,
>>> 
>>> I want to create a mini http server project and execute at Ubuntu 15. The 
>>> Xcode compile and access the function "autoreleasepool", but when i compile 
>>> the same code at Ubuntu, this function not found
>>> 
>>> For example, i can compile the code above at Xcode:
>>> 
>>> while true {
>>>autoreleasepool {
>>>var test: Data = "HTTP/1.1 200 OK\r\nContent-Length: 
>>> 1\r\n\r\na".data(using: .utf8)!
>>>}
>>> }
>>> 
>>> But when i try to compile at Ubuntu:
>>> 
>>> git@breder:~$ cat main.swift 
>>> import Foundation
>>> 
>>> while true {
>>>autoreleasepool {
>>>var test: Data = "HTTP/1.1 200 OK\r\nContent-Length: 
>>> 1\r\n\r\na".data(using: .utf8)!
>>>}
>>> }
>>> 
>>> git@breder:~$ swiftc main.swift 
>>> main.swift:4:5: error: use of unresolved identifier 'autoreleasepool'
>>>autoreleasepool {
>>>^~~
>> 
>> Autoreleasepools are an ObjC compatibility feature. They aren't necessary in 
>> standalone Swift.
> 
> But they are necessary in Swift programs on Apple platforms (that don’t use 
> RunLoop, anyway). Philippe, what do you think? What’s the right way to write 
> cross-platform code that doesn’t use RunLoop or dispatch_main for an implicit 
> autorelease pool?
> 
> (/me remembers +[NSAutoreleasePool drain] from the ObjC-GC days)

If you must, you could conditionally define `autoreleasepool` to just call its 
argument as a compatibility shim.

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


Re: [swift-users] Autoreleasepool for Ubuntu

2016-11-02 Thread Joe Groff via swift-users

> On Nov 1, 2016, at 6:40 PM, Bernardo Breder via swift-users 
>  wrote:
> 
> Hello,
> 
> I want to create a mini http server project and execute at Ubuntu 15. The 
> Xcode compile and access the function "autoreleasepool", but when i compile 
> the same code at Ubuntu, this function not found
> 
> For example, i can compile the code above at Xcode:
> 
> while true {
> autoreleasepool {
> var test: Data = "HTTP/1.1 200 OK\r\nContent-Length: 
> 1\r\n\r\na".data(using: .utf8)!
> }
> }
> 
> But when i try to compile at Ubuntu:
> 
> git@breder:~$ cat main.swift 
> import Foundation
> 
> while true {
> autoreleasepool {
> var test: Data = "HTTP/1.1 200 OK\r\nContent-Length: 
> 1\r\n\r\na".data(using: .utf8)!
> }
> }
> 
> git@breder:~$ swiftc main.swift 
> main.swift:4:5: error: use of unresolved identifier 'autoreleasepool'
> autoreleasepool {
> ^~~

Autoreleasepools are an ObjC compatibility feature. They aren't necessary in 
standalone Swift.

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


Re: [swift-users] IUO from C Library Interface

2016-10-24 Thread Joe Groff via swift-users

> On Oct 24, 2016, at 3:09 PM, Ryan Lovelett  wrote:
> 
>> Not being able to assign the function reference is a bug. As a
>> workaround, you should be able to unsafeBitCast CC_SHA1_Update to the
>> appropriate type.
>> 
>> -Joe
> 
> Two questions:
> 
> 1. Is this an already reported bug? If so, would you happen to know what
> it is so I can track it for resolution (to remove the work-around when
> it is resolved)?
> 
> I made the protocol def this:
> var bar: (UnsafeMutablePointer?, UnsafeRawPointer?, CC_LONG) ->
> Int32 { get }
> 
> Then the imp this:
> let bar = unsafeBitCast(CC_SHA1_Update, to:
> ((UnsafeMutablePointer?, UnsafeRawPointer?, CC_LONG) ->
> Int32).self)

I don't believe we have a bug for this issue yet. The intent for IUO in Swift 3 
is that it acts only as a modifier for declarations; as parts of types, it's 
equivalent to Optional. A function reference like CC_SHA1_Update should 
formally have Optional typed parameters.

> 2. Perhaps I'm doing something wrong here but I feel like this just make
> the code less safe. It seems now I can send in an optional, read: nil,
> pointer to this `bar` method. On face, this seems dangerous. The
> `CC_SHA1_Update` method seems explicit in that it will not deal with
> `nil`. So it seems that this thing is now reporting a safer API than
> what is actually there. Or did I misunderstand? Should I be dropping the
> IUO all together and just make it `UnsafeMutablePointer` and
> `UnsafeRawPointer`?

We imported the function as IUO because we don't have any information one way 
or the other from the original C code about whether it takes nil or not. It's 
up to you not to pass in 'nil' if it doesn't accept 'nil'.

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


Re: [swift-users] IUO from C Library Interface

2016-10-24 Thread Joe Groff via swift-users

> On Oct 24, 2016, at 2:24 PM, Ryan Lovelett via swift-users 
>  wrote:
> 
> import CommonCrypto
> 
> protocol Foo {
>  associatedtype Context
>  var context: Context { get set }
>  var bar: (UnsafeMutablePointer!, UnsafeRawPointer!, CC_LONG)
>  -> Int32 { get }
> }
> 
> struct SHA1: Foo {
>  var context: CC_SHA1_CTX
>  var bar: (UnsafeMutablePointer!, UnsafeRawPointer!,
>  CC_LONG) -> Int32 = CC_SHA1_Update
> }
> 
> Unfortunately this will not compile any longer with Swift 3.0. The error
> is: Implicitly unwrapped optionals are only allowed at top level and as
> function results.
> 
> I can try modifying `bar` definition to be `?` instead of `!` but then
> `CC_SHA1_Update`) can no longer be assigned to `bar`.
> 
> Suggestions?

Not being able to assign the function reference is a bug. As a workaround, you 
should be able to unsafeBitCast CC_SHA1_Update to the appropriate type.

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


Re: [swift-users] Overload by return type optionality?

2016-10-13 Thread Joe Groff via swift-users

> On Oct 13, 2016, at 3:27 PM, Rick Mann  wrote:
> 
>> 
>> On Oct 13, 2016, at 14:47 , Joe Groff  wrote:
>> 
>> 
>>> On Oct 13, 2016, at 2:36 PM, Rick Mann via swift-users 
>>>  wrote:
>>> 
>>> It seems I can write this:
>>> 
>>> extension String
>>> {
>>> public func deleting(prefix inPrefix: String) -> String
>>> public func deleting(prefix inPrefix: String) -> String?
>>> }
>>> 
>>> But I was hoping it would do the right thing:
>>> 
>>> let a = s.deleting(prefix: "foo")
>>> if let b = s.deleting(prefix: "foo") { }
>>> 
>>> But it finds these ambiguous, and I'm not sure how to specify which I want.
>> 
>> The first one is truly ambiguous since either overload works. If you specify 
>> the type of 'a', you should be able to choose one or the other:
>> 
>> let a: String = s.deleting(prefix: "foo")
>> let b: String? = s.deleting(prefix: "foo")
>> 
>> The `if let` should not be ambiguous, since only the Optional-returning 
>> overload is a valid candidate. Got time to file a bug?
> 
> Here you go: https://bugs.swift.org/browse/SR-2942

Thanks!

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


Re: [swift-users] Data reflection metadata?

2016-10-13 Thread Joe Groff via swift-users

> On Oct 13, 2016, at 9:19 AM, Austin Zheng via swift-users 
>  wrote:
> 
> You probably want to check out this repo: https://github.com/Zewo/Reflection
> 
> It's clever stuff. Really, really reliant on implementation details of the 
> runtime to function, so I'd be loathe to use it in any sort of production 
> application, but as a proof of concept it shines.

From what I've seen, they're groveling our runtime metadata records, which are 
definitely subject to change without notice. I wouldn't recommend following 
their example, since we actively want to change the layout of things they're 
hardcoding. What Chris was referring to was the "remote mirror" library, which 
is used to support the Xcode 8 memory debugger, and is also in the long-term 
what we want to migrate in-process reflection facilities like the Mirror type 
to. The `swift-reflection-test` and `swift-reflection-dump` tools in the Swift 
compiler codebase might help give you a sense of what's currently available:

https://github.com/apple/swift/blob/master/tools/swift-reflection-test
https://github.com/apple/swift/tree/master/tools/swift-reflection-dump

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


Re: [swift-users] Why are Swift Loops slow?

2016-10-12 Thread Joe Groff via swift-users

> On Oct 12, 2016, at 2:25 AM, Gerriet M. Denkmann via swift-users 
>  wrote:
> 
> uint64_t nbrBytes = 4e8;
> uint64_t count = 0;
> for( uint64_t byteIndex = 0; byteIndex < nbrBytes; byteIndex++ )
> {
>   count += byteIndex;
>   if ( ( byteIndex & 0x ) == 0 ) { count += 1.3; }  (AAA) 
> };
> 
> Takes 260 msec.
> 
> Btw.: Without the (AAA) line the whole loop is done in 10 μsec. A really 
> clever compiler!
> And with “count += 1” instead of “count += 1.3” it takes 410 msec. Very 
> strange. 
> But this is beside the point here.
> 
> 
> Now Swift:
> let nbrBytes = 400_000_000
> var count = 0
> for byteIndex in 0 ..< nbrBytes
> {
>   count += byteIndex
>   if ( ( byteIndex & 0x ) == 0 ) {count += Int(1.3);}
> }
> 
> takes 390 msec - about 50 % more.
> 
> Release build with default options.

This is a useless benchmark because the loop does no observable work in either 
language. The C version, if you look at the generated assembly, in fact 
optimizes away to nothing:

~/src/s/swift$ clang ~/butt.c -O3  -S -o -
.section__TEXT,__text,regular,pure_instructions
.macosx_version_min 10, 9
.globl  _main
.p2align4, 0x90
_main:  ## @main
.cfi_startproc
## BB#0:## %entry
pushq   %rbp
Ltmp0:
.cfi_def_cfa_offset 16
Ltmp1:
.cfi_offset %rbp, -16
movq%rsp, %rbp
Ltmp2:
.cfi_def_cfa_register %rbp
xorl%eax, %eax
popq%rbp
retq
.cfi_endproc

It looks like LLVM does not recognize the overflow traps Swift emits on 
arithmetic operations as dead code, so that prevents it from completely 
eliminating the Swift loop.  That's a bug worth fixing in Swift, but unlikely 
to make a major difference in real, non-dead code. However, if we make the work 
useful by factoring the loop into a function in both languages, the perf 
difference is unmeasurable. Try comparing:

#include 

__attribute__((noinline))
uint64_t getCount(uint64_t nbrBytes) {
  uint64_t count = 0;
  for( uint64_t byteIndex = 0; byteIndex < nbrBytes; byteIndex++ )
  {
  count += byteIndex;
  if ( ( byteIndex & 0x ) == 0 ) { count += 1.3; } 
  };
  return count;
}

int main() {
  uint64_t nbrBytes = 4e8;
  return getCount(nbrBytes);
}


with:

import Darwin

@inline(never)
func getCount(nbrBytes: Int) -> Int {
  var count = 0
  for byteIndex in 0 ..< nbrBytes
  {
  count += byteIndex
  if ( ( byteIndex & 0x ) == 0 ) {count += Int(1.3);}
  }
  return count
}

exit(Int32(truncatingBitPattern: getCount(nbrBytes: 400_000_000)))

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


Re: [swift-users] Casting tuples to protocols always fails (and the compiler should know)

2016-10-10 Thread Joe Groff via swift-users

> On Oct 10, 2016, at 8:20 AM, Sebastian Hagedorn via swift-users 
>  wrote:
> 
> We encountered a very surprising behaviour in one of our apps, and believe 
> it’s a bug/missing warning in the Swift compilter, but it would be great if 
> someone could confirm we’re not missing a piece before I file a bug report.
> 
> This snippet reproduces the issue:
> 
> protocol MyProto {
>var title: String? { get }
> }
> 
> let tuple = (x: 100, y: 100)
> 
> // Results in a warning as expected: Cast always fails
> let castedTupleToInt = tuple as? Int
> 
> // No warning, although cast will always fail
> let castedTuple = tuple as? MyProto
> 
> The way I see it, it should be pretty easy for the compiler to detect that 
> casting a tuple to a protocol always fails, since there’s no way for a tuple 
> to conform to a protocol.
> 
> We came across the bug when we refactored a method to return a tuple instead 
> of a protocol type, and thought the compiler would make us aware of all the 
> call sites that need to adopt the the refactored return type. However, 
> wherever we casted the return type, no warning was raised and the code just 
> silently returned early because the cast always fails at runtime (as it 
> should, of course).

In general, we can't say that a cast to protocol type always fails, since some 
other module in your program could extend the type to conform to the protocol. 
Although tuples aren't allowed to conform to protocols today, that's not a 
fundamental limitation we intend to live with forever.

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


Re: [swift-users] C interop: passing null pointers to unwrapped unsafe pointers

2016-10-07 Thread Joe Groff via swift-users

> On Oct 7, 2016, at 7:02 AM, Ingo Maier via swift-users 
>  wrote:
> 
> Is there a way in Swift 3 to pass a null pointer to a C function that
> takes an implicitly unwrapped unsafe pointer? I understand that
> pointer parameters in C that don't specify nullability are mapped to
> implicitly unwrapped pointers in Swift 3. Since it's not uncommon for
> existing unannotated C APIs to accept null pointers, I assume there
> has to be a way other than creating my own bridge functions in C. I
> hope I am not wrong.
> 
> I am a bit surprised that I couldn't find an answer to this, neither
> on this list nor on stackoverflow, as I presume I am not the only one
> with this problem. Sorry, if I missed something.

An implicitly unwrapped Optional is still an Optional. You can use `nil` to 
pass a null pointer.

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


Re: [swift-users] Different behaviour when casting Float and Double to NSNumber

2016-10-05 Thread Joe Groff via swift-users

> On Oct 5, 2016, at 2:30 AM, Lars-Jørgen Kristiansen via swift-users 
>  wrote:
> 
> I'm working with a third party API for some external hardware. One of the 
> functions takes a NSNumber, and it fails to interact correctly with the 
> hardware if I cast a Float too NSNumber, but works as expected if I use 
> Double..
> 
> I dont know if it is related to NSNumber.stringValue since I dont know what 
> the third part lib does with the NSNumber, but I noticed this:
> 
> let float = 100_000_00 as Float
> let floatNumber = float as NSNumber
> 
> let double = 100_000_00 as Double
> let doubleNumer = double as NSNumber
> 
> hardware.doThing(number: floatNumber as NSNumber) // Hardware does not work
> hardware.doThing(number: doubleNumer as NSNumber) // Hardware works
> 
> // Also noticed this:
> "\(floatNumber)" // "1e+07"
> "\(doubleNumer)" // "1000"
> 
> Is this expected behaviour?

cc'ing Tony and Philippe, who might be able to comment on the intended behavior 
of NSNumber here. When you cast using `as`, Swift will do the conversion 
through its Objective-C bridge, and will attempt to use a custom subclass of 
NSNumber that remembers the exact Swift type it was bridged as, such as Float 
or Double. There's a small chance your library is making assumptions that it's 
working with one of the standard NSNumber subclasses used by the Foundation 
implementation. If you call the NSNumber initializer `NSNumber(value: 
floatNumber)` instead of using the `as` conversion, you'll get one of these 
standard NSNumbers instead of a Swift-bridged NSNumber. Try that and see if it 
works. If using the initializer does indeed fix the problem, we'd appreciate a 
bug report, so we can investigate fixing the incompatibility with our NSNumber 
subclasses.

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


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

2016-10-04 Thread Joe Groff via swift-users

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

Thanks!

-Joe

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


Re: [swift-users] UnsafeMutablePointer on the stack?

2016-10-03 Thread Joe Groff via swift-users

> On Oct 3, 2016, at 10:20 AM, Jens Alfke via swift-users 
>  wrote:
> 
> 
>> On Oct 2, 2016, at 5:14 PM, Mike Ferenduros via swift-users 
>> > wrote:
>> 
>> Personally I would be surprised if the malloc caused an actual measurable 
>> performance hit tbh.
> 
> It won’t be noticeable against a call to SecRandom, as noted, but there are 
> other circumstances where it’s a big performance hit to put a temporary 
> buffer on the heap. (Right now I’m working on some rather 
> performance-sensitive database code in C++ where avoiding a few heap 
> allocations per iteration has proven to be a big win.)
> 
> Does Swift have any solution for allocating stack-based array buffers?

There has been some work in the optimizer toward optimizing arrays onto the 
stack when they don't escape. In general, I would recommend sticking with the 
pointer allocate/deallocate methods if you need to directly control the destiny 
of the memory. If the allocate and deallocate occur unconditionally in the same 
function, it is possible to optimize the pair into a stack allocation. Using a 
local variable isn't a guarantee that you'll get stack memory, since closures 
may force the variable onto the heap, and furthermore subjects you to more 
aggressive semantic constraints on the underlying memory than you may want.

-Joe

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


Re: [swift-users] How to malloc in Swift 3

2016-09-23 Thread Joe Groff via swift-users

> On Sep 23, 2016, at 2:20 PM, Jens Persson  wrote:
> 
> What is the difference between:
> ptr.storeBytes(of: x, toByteOffset: offset, as: type(of: x))
> ptr.advanced(by: offset).assumingMemoryBound(to: type(of: x)).pointee = x
> ?
> I noticed that the former traps if storing to a misaligned offset while the 
> latter is happy to do that, and I saw it mentioned as a requirement in the 
> documentation, but other than that I'm not sure what would be the pros and 
> cons of using the former / latter?

cc'ing Andy, who's the expert on this. AIUI, the former does not semantically 
bind the memory to the type being stored—informally, it has "memcpy 
semantics"—whereas the latter *will* bind the memory to a type, which will 
require all other loads and stores derived from the same pointer to remain of 
the same type. Neither API officially supports unaligned loads or stores yet; 
if one crashes and the other doesn't, that's an accident.

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


Re: [swift-users] How to malloc in Swift 3

2016-09-23 Thread Joe Groff via swift-users

> On Sep 23, 2016, at 1:55 AM, Gerriet M. Denkmann via swift-users 
>  wrote:
> 
> 
>> On 23 Sep 2016, at 15:47, Gerriet M. Denkmann via swift-users 
>>  wrote:
>> 
>> This used to work in Swift 2.2:
>> 
>> var bitfield: UnsafeMutablePointer?
>> bitfield = UnsafeMutablePointer( malloc( 888 ) )
>> 
>> How is this written in Swift 3.0?
> 
> To answer my own question:
> This works:
> var bitfield: UnsafeMutableRawPointer 
> bitfield = UnsafeMutableRawPointer( malloc(888))
> 
> But then this stops working:
> let theByte = self.bitfield[ 5 ] 
> 
> Somehow the bitfield must know that it is a field of bytes (not shorts, ints 
> or whatever). But how?

The RawPointer types provide methods that can load a value with a given offset 
and type for you. IIRC, `bitfield.load(fromByteOffset: 0, as: UInt8.self)` will 
do what you want.

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


Re: [swift-users] Swift 3 likes to tease me

2016-09-23 Thread Joe Groff via swift-users

> On Sep 22, 2016, at 9:51 PM, Gerriet M. Denkmann via swift-users 
>  wrote:
> 
> This line (Swift 3):
>   if a.responds(to: Selector(“viewControllers") )
> creates this warning: Use '#selector' instead of explicitly constructing a 
> 'Selector'
> 
> Ok. Following this advice I change it to:
>   if a.responds(to: #selector(“viewControllers"))
> and now get an error instead: Argument of ‘#selector' does not refer to an 
> '@objc' method, property, or initializer

Others have answered your question, but this looks to me like an opportunity 
for us to improve the error message. Attempting to use #selector() with a 
string literal like this seems like a natural thing to try, and we could offer 
better diagnostics for this case. If you have a moment, would you be able to 
file a bug to improve the diagnostics in this case?

-Joe

> Why do I get punished for following Xcode’s advice?
> 
> Gerriet.
> 
> ___
> 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] NSData vs Data write to string differently?

2016-09-22 Thread Joe Groff via swift-users

> On Sep 22, 2016, at 4:04 PM, Shawn Erickson via swift-users 
>  wrote:
> 
> In general you shouldn't depend on what description returns for classes, etc. 
> outside of your control unless it is documented (e.g. part of the API 
> contract). If you want a specific output you should code up something to 
> format the output as you need.

This is good advice, but the printing behavior of Data nonetheless strikes me 
as a bug. NSData's printing behavior seems much more useful than Data's. If 
either of you have a moment, would you be able to file a bug about this?

-Joe

> -Shawn
> 
> On Thu, Sep 22, 2016 at 3:33 PM Robert Nikander via swift-users 
>  wrote:
> Hi,
> 
> I’ve run into a problem when updating to new Swift in Xcode 8. There was some 
> NSData in a string like this:
> 
> “ … \(data) … “
> 
> It changed to type `Data`, and the string went from hexadecimal bytes to 
> writing “20 bytes”. I’m doing a quick bug fix app release now. I can’t 
> remember if Xcode auto converted this for me. I thought it did.  ?  Either 
> way… seems like they should behave the same here, no?
> 
> Rob
> 
> 
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

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


Re: [swift-users] Can anyone please explain this behavior?

2016-09-22 Thread Joe Groff via swift-users

> On Sep 22, 2016, at 11:28 AM, Jens Persson  wrote:
> 
> Yes, but should the compiler silently accept that? And is this issue really 
> related to the other issue?

No, this is a separate issue. The compiler might be able to catch some obvious 
cases, but it'd be impossible to statically prevent all circularities. The 
runtime could probably do a better job detecting this situation, though, and 
give a runtime error instead of just letting the deadlock happen.

-Joe

> /Jens
> 
> On Thu, Sep 22, 2016 at 8:23 PM, Joe Groff  wrote:
> 
> > On Sep 22, 2016, at 11:23 AM, Jens Persson  wrote:
> >
> > Oh, but how can the following (earlier mentioned) example have anything to 
> > do with Script-mode top-level locals being treated as globals?
> >
> > Create "AnotherFile.swift" containing:
> > func f() -> Int { return a }
> > let a = f()
> 
> In this case, you have a deadlock, since the initialization of `a` depends on 
> its own initialization.
> 
> -Joe
> 
> > Create "main.swift" containing:
> > print(a)
> >
> > Compile. Run. For ever. At zero % CPU.
> >
> > /Jens
> >
> >
> >
> > On Thu, Sep 22, 2016 at 8:03 PM, Jens Persson  wrote:
> > Thank you for the thorough explanation!
> > /Jens
> >
> > On Thu, Sep 22, 2016 at 7:28 PM, Jordan Rose  wrote:
> > Yep, it really is a long-standing bug. Script-mode top-level locals are 
> > treated as globals (module-scope bindings) by the compiler, but their 
> > initial bindings are evaluated eagerly instead of lazily (as you’d want in 
> > a script). Taken together, this means that you can get this completely 
> > unsafe behavior.
> >
> > So, why is ‘a’ accepted but ‘b’ not in your original example?
> >
> >> func foo() -> Int { return b }
> >> let a = 1
> >> let b = 2
> >> print(foo())
> >
> > The secret to the current behavior is that script mode is executed 
> > interactively, instead of parsing it all up front. To make things a little 
> > better, it actually parses any number of declarations until it sees 
> > something it actually needs to execute—a statement or a declaration with an 
> > initial value expression. This allows for recursive functions while still 
> > being “live”.
> >
> > The consequence here is that one top-level binding after a series of 
> > functions may be visible. This is obviously not optimal.
> >
> > To fix this, we should:
> >
> > - Distinguish between script-mode top-level locals and module-scope 
> > variables that happen to be declared. My personal preference is to treat 
> > anything with explicit access control as a normal lazy global and anything 
> > without access as a top-level local.
> >
> > - Consider parsing everything up front, even if we don’t type-check it, so 
> > that we can say “use of ‘b’ before it’s initialized” instead of “undeclared 
> > name ‘b’”
> >
> > Note that we do need to be conservative here. This code should continue to 
> > be rejected, even though ‘f’ doesn’t refer to ‘local’ directly, because 
> > calling ‘f' would be dangerous before the initialization of ‘local':
> >
> > internal func f() -> Int {
> >   return g()
> > }
> > // more code here
> >
> > let local = 42
> > private func g() -> Int {
> >   return local
> > }
> >
> > Thanks for bringing this up, if only so I have an opportunity to write out 
> > the issue. :-)
> > Jordan
> >
> >
> >> On Sep 21, 2016, at 23:04, Jens Persson  wrote:
> >>
> >> Did you see the other code examples that came up in that twitter 
> >> conversations?
> >> For example:
> >>
> >> This worrying little program compiles:
> >> func f() -> Int {
> >> return a
> >> }
> >> let a = f()
> >>
> >>
> >> It also compiles if you print(a) at the end, and it will print 0.
> >>
> >> If we replace Int with [Int] it will still compile but crash when run.
> >>
> >> And also this:
> >>
> >> AnotherFile.swift containing:
> >> func f() -> Int {
> >> return a
> >> }
> >> let a = f()
> >>
> >> main.swift containing
> >> print(a)
> >>
> >> Compile, run (for eternity, at 0% CPU).
> >>
> >> /Jens
> >>
> >>
> >> On Thu, Sep 22, 2016 at 3:13 AM, Joe Groff  wrote:
> >>
> >> > On Sep 21, 2016, at 2:22 PM, Jens Persson via swift-users 
> >> >  wrote:
> >> >
> >> > // This little Swift program compiles (and runs) fine:
> >> >
> >> > func foo() -> Int { return a }
> >> > let a = 1
> >> > let b = 2
> >> > print(foo())
> >> >
> >> > But if `foo()` returns `b` instead of `a`, I get this compile time error:
> >> > "Use of unresolved identifier `b`"
> >>
> >> This looks like a bug to me (cc-ing Jordan, who's thought about global 
> >> scoping issues more than me). In "script mode", it shouldn't be possible 
> >> to refer to a variable before its initialization is executed. However, the 
> >> way this is currently modeled is…problematic, to say the least, among 
> >> other reasons because script globals are still visible to "library" files 
> >> in the 

Re: [swift-users] Can anyone please explain this behavior?

2016-09-22 Thread Joe Groff via swift-users

> On Sep 22, 2016, at 11:23 AM, Jens Persson  wrote:
> 
> Oh, but how can the following (earlier mentioned) example have anything to do 
> with Script-mode top-level locals being treated as globals?
> 
> Create "AnotherFile.swift" containing:
> func f() -> Int { return a }
> let a = f()

In this case, you have a deadlock, since the initialization of `a` depends on 
its own initialization.

-Joe

> Create "main.swift" containing:
> print(a)
> 
> Compile. Run. For ever. At zero % CPU.
> 
> /Jens
> 
> 
> 
> On Thu, Sep 22, 2016 at 8:03 PM, Jens Persson  wrote:
> Thank you for the thorough explanation!
> /Jens
> 
> On Thu, Sep 22, 2016 at 7:28 PM, Jordan Rose  wrote:
> Yep, it really is a long-standing bug. Script-mode top-level locals are 
> treated as globals (module-scope bindings) by the compiler, but their initial 
> bindings are evaluated eagerly instead of lazily (as you’d want in a script). 
> Taken together, this means that you can get this completely unsafe behavior.
> 
> So, why is ‘a’ accepted but ‘b’ not in your original example?
> 
>> func foo() -> Int { return b }
>> let a = 1
>> let b = 2
>> print(foo())
> 
> The secret to the current behavior is that script mode is executed 
> interactively, instead of parsing it all up front. To make things a little 
> better, it actually parses any number of declarations until it sees something 
> it actually needs to execute—a statement or a declaration with an initial 
> value expression. This allows for recursive functions while still being 
> “live”.
> 
> The consequence here is that one top-level binding after a series of 
> functions may be visible. This is obviously not optimal.
> 
> To fix this, we should:
> 
> - Distinguish between script-mode top-level locals and module-scope variables 
> that happen to be declared. My personal preference is to treat anything with 
> explicit access control as a normal lazy global and anything without access 
> as a top-level local.
> 
> - Consider parsing everything up front, even if we don’t type-check it, so 
> that we can say “use of ‘b’ before it’s initialized” instead of “undeclared 
> name ‘b’”
> 
> Note that we do need to be conservative here. This code should continue to be 
> rejected, even though ‘f’ doesn’t refer to ‘local’ directly, because calling 
> ‘f' would be dangerous before the initialization of ‘local':
> 
> internal func f() -> Int {
>   return g()
> }
> // more code here
> 
> let local = 42
> private func g() -> Int {
>   return local
> }
> 
> Thanks for bringing this up, if only so I have an opportunity to write out 
> the issue. :-)
> Jordan
> 
> 
>> On Sep 21, 2016, at 23:04, Jens Persson  wrote:
>> 
>> Did you see the other code examples that came up in that twitter 
>> conversations?
>> For example:
>> 
>> This worrying little program compiles:
>> func f() -> Int {
>> return a
>> }
>> let a = f()
>> 
>> 
>> It also compiles if you print(a) at the end, and it will print 0.
>> 
>> If we replace Int with [Int] it will still compile but crash when run.
>> 
>> And also this:
>> 
>> AnotherFile.swift containing:
>> func f() -> Int {
>> return a
>> }
>> let a = f()
>> 
>> main.swift containing
>> print(a)
>> 
>> Compile, run (for eternity, at 0% CPU).
>> 
>> /Jens
>> 
>> 
>> On Thu, Sep 22, 2016 at 3:13 AM, Joe Groff  wrote:
>> 
>> > On Sep 21, 2016, at 2:22 PM, Jens Persson via swift-users 
>> >  wrote:
>> >
>> > // This little Swift program compiles (and runs) fine:
>> >
>> > func foo() -> Int { return a }
>> > let a = 1
>> > let b = 2
>> > print(foo())
>> >
>> > But if `foo()` returns `b` instead of `a`, I get this compile time error:
>> > "Use of unresolved identifier `b`"
>> 
>> This looks like a bug to me (cc-ing Jordan, who's thought about global 
>> scoping issues more than me). In "script mode", it shouldn't be possible to 
>> refer to a variable before its initialization is executed. However, the way 
>> this is currently modeled is…problematic, to say the least, among other 
>> reasons because script globals are still visible to "library" files in the 
>> same module.
>> 
>> -Joe
>> 
> 
> 
> 

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


[swift-users] Fwd: How to bridge between CoreFoundation and SwiftFoundation on Linux?

2016-09-21 Thread Joe Groff via swift-users

> On Sep 21, 2016, at 1:03 PM, Bouke Haarsma via swift-users 
>  wrote:
> 
> The one that comes with SwiftFoundation 
> (https://github.com/apple/swift-corelibs-foundation/tree/master/CoreFoundation).
> 
> I think it should be a bug that CFReadStream cannot be bridged to 
> (NS)InputStream, as otherwise there’s no way to intertwine Sockets 
> (CFSockets) with SwiftFoundation. As the implementation already uses a 
> CFReadStream internally 
> (https://github.com/apple/swift-corelibs-foundation/blob/d3872cb094124d5dd189839505ae73e2fa717cfd/Foundation/NSStream.swift#L122),
>  it would be a matter of adding an initializer. However the value is private, 
> so adding the initializer cannot be done from an extension.

(including the list this time) AIUI, Core Foundation is an implementation 
detail of the corelibs implementation of Foundation. It isn't intended to be 
used directly from Swift code on Linux.

-Joe

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


Re: [swift-users] Can anyone please explain this behavior?

2016-09-21 Thread Joe Groff via swift-users

> On Sep 21, 2016, at 2:22 PM, Jens Persson via swift-users 
>  wrote:
> 
> // This little Swift program compiles (and runs) fine:
> 
> func foo() -> Int { return a }
> let a = 1
> let b = 2
> print(foo())
> 
> But if `foo()` returns `b` instead of `a`, I get this compile time error:
> "Use of unresolved identifier `b`"

This looks like a bug to me (cc-ing Jordan, who's thought about global scoping 
issues more than me). In "script mode", it shouldn't be possible to refer to a 
variable before its initialization is executed. However, the way this is 
currently modeled is…problematic, to say the least, among other reasons because 
script globals are still visible to "library" files in the same module.

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


Re: [swift-users] Argument type 'Int' does not conform to expected type 'AnyObject'

2016-09-09 Thread Joe Groff via swift-users

> On Sep 9, 2016, at 2:02 PM, Kevin Nattinger via swift-users 
>  wrote:
> 
> You’ll need to explicitly add the “as NSNumber” now.
> 
> https://github.com/apple/swift-evolution/blob/master/proposals/0072-eliminate-implicit-bridging-conversions.md

Or even better, you should now be able to use `Any` in Swift 3 in most places 
Swift 2 required `AnyObject`. Swift now handles the object conversion as part 
of the runtime Objective-C bridge, so these weird special-case implicit 
conversions should not be necessary in most cases anymore.

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


Re: [swift-users] Defer with local variable's state

2016-08-11 Thread Joe Groff via swift-users

> On Aug 11, 2016, at 7:16 AM, Sebastian Hagedorn via swift-users 
>  wrote:
> 
> We often write code that returns early, but has to make sure a bit of code 
> (e.g., a completion handler) is always called whenever we return, which seems 
> like a great use case for defer. I started to write this:
> 
> func execute(with completion: ((Bool) -> Void)?) {
>   var success = false
>   defer {
>   // should always execute with the current state of success at 
> that time
>   completion?(success)
>   }
> 
>   guard … else {
>   // completion is expected to be executed with false
>   return
>   }
> 
>   success = true
> 
>   // completion is expected to be executed with true
> }
> 
> However, it seems that defer copies the state of success, which means any 
> update to the variable is not respected, and the completion block is always 
> called with false.
> 
> Is there a way to make this work? I could image to call a function within the 
> defer block that evaluates the success (e.g., depending on the state of an 
> instance variable), but using a local variable seems to encapsulate this a 
> lot better.

This is a bug. Defer should track updates of the variable. Would you mind 
filing this at bugs.swift.org? Do you happen to know whether it reproduces only 
in debug or release builds, or both?

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


Re: [swift-users] Set size of byte array

2016-08-09 Thread Joe Groff via swift-users

> On Aug 5, 2016, at 9:42 AM, KS Sreeram via swift-users 
>  wrote:
> 
> 
>> On 05-Aug-2016, at 1:19 PM, Daniel Vollmer  wrote:
>> 
>> I’m by no means a Swift expert (not even a user at the moment), but I don't
>> see a way to do this either. The best that comes to mind is initializing a
>> ContiguousArray with the sufficient capacity as size, using
>> withUnsafeBufferPointer to overwrite elements, and then use replaceAll() with
>> an empty collection to remove the excess size.
> 
> The only initializer that could help with this is: 
> init(count:repeatedValue:). Unfortunately, this means the buffer is written 
> to twice - once in the initializer, and a second time to actually fill in the 
> data. It’s not efficient.
> 
>> 
>> I'd think that just reserving enough capacity and then appending the elements
>> one-by-one will be (at least?) as efficient: The byte is always copied 
>> anyway,
>> and in this case you wouldn’t have to default-construct the capacity 
>> beforehand.
> 
> This too isn’t efficient because each append call will incur an the cost of 
> checking for sufficient capacity and also incrementing the size. The 
> additional penalty could dwarf the cost of actually copying a byte! I don’t 
> think the compiler is capable of removing this inefficiency.

cc-ing Arnold, who owns this part of the optimizer. IIRC we are able to hoist 
the capacity check in 'append' loops in some cases.

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


Re: [swift-users] Chaining struct-mutating funcs

2016-08-05 Thread Joe Groff via swift-users
Since your backing buffer is copy-on-write, you can do the in-place mutation 
optimization in your immutable implementations, something like this:

class C {
  var value: Int
  init(value: Int) { self.value = value }
}

struct S { var c: C }

func addInts(x: S, y: S) -> S {
  var tmp = x
  // Don't use x after this point so that it gets forwarded into tmp
  if isKnownUniquelyReferenced() {
tmp.c.value += y.c.value
return tmp
  } else {
return S(c: C(value: tmp.c.value + y.c.value))
  }
}

which should let you get similar efficiency to the mutating formulation while 
using semantically immutable values.

-Joe

> On Aug 5, 2016, at 2:35 PM, Fritz Anderson via swift-users 
>  wrote:
> 
> Swift 3 as of Xcode 8.0b4
> 
> TL;DR: I have a struct value type backed by a copy-on-write mutable buffer. 
> You use it to perform arithmetic on the buffers. The most expressive way to 
> do this efficiently is to chain the arithmetic operators so each mutates the 
> same buffer. Swift does not like to chain mutating operators — it treats the 
> result of each step as immutable, so you can’t continue the chain. I can’t 
> argue; the syntax apparently can't express anything else.
> 
> All the alternatives I see are ugly-to-dangerous.
> 
> Have I missed something, I hope? Please make a fool of me.
> 
>   — F
> 
> The details of my use case or implementation are off-topic; even if mine are 
> ill-considered, surely apt ones exist. Unless you can demonstrate there are 
> none.
> 
> The vDSP_* functions in Apple’s Accelerate framework are declared in C to 
> operate on naked float or double pointers. I decided to represent such Float 
> buffers in Swift by a struct (call it ManagedFloatBuffer) containing a 
> reference to a FloatBuffer, which is a final specialization of class 
> ManagedBuffer.
> 
> (The names are a work-in-progress. Just remember: ManagedFloatBuffer is a 
> value type that can copy-on-write to a reference to FloatBuffer, a backing 
> store for a bunch of Floats.)
> 
> The nonmutating funcs:
> 
> func subtract(_ other: ManagedFloatBuffer) -> ManagedFloatBuffer
> func subtract(_ scalar: Float) -> ManagedFloatBuffer
> 
> are straightforward. They return new ManagedFloatBuffer values. You can chain 
> further calls to simplify a complex calculation that is neither intricate nor 
> tied up in temporaries:
> 
> let sum²OfResiduals = speeds
> .subtract(cameraSpeed.mean)
> .multiply(feetToMeters)
> .sumOfSquares
> 
> Great. And vDSP gets you about a 40% boost. (The compiler itself seems to do 
> a pretty good job of auto-vectorizing; the unoptimized code is a couple of 
> orders of magnitude slower.) But as you chain the immutables, you generate 
> new FloatBuffers to hold the intermediate results. For long chains, you end 
> up allocating new buffers (which turns out to be expensive on the time scale 
> of vectorized math) and copying large buffers into them that you are about to 
> discard. I want my Swift code to be as performant as C, but safer and more 
> expressive.
> 
> So how about some mutating functions to change a ManagedFloatBuffer’s bytes 
> in-place (copying-on-write as needed so you can preserve intermediate values)?
> 
> mutating func reduce(by other: ManagedFloatBuffer) -> ManagedFloatBuffer
> mutating func reduce(by scalar: Float) -> ManagedFloatBuffer
> 
> These return self, because I’d hoped I could chain operators as I did with 
> the non-mutating versions.
> 
> The compiler doesn’t like this. It says reduce(by:) returns an immutable 
> value, so you can’t chain mutating functions.
> 
> (I can see an issue in that when the first func's self is copied as the 
> return value that is used as the second func’s self,  that could make two 
> surviving references to the same buffer, so a buffer copy would happen when 
> you mutate the second func’s self anyway. I’m not sure the compiler has to do 
> that, but I can see how it might be hard to account for otherwise. Hey, it’s 
> a tail call, right? SMOP, not source-breaking at all.)
> 
> StackOverflow invites me to eat cake: Make the mutable operand inout to funcs 
> I call one by one. Something like:
> 
> multiply(perspectiveCorrections, into: )
> sin(of: )
> multiply(pixelXes, into: )
> multiply(feetToMeters, into: )
> subtract(cameraSpeed.mean, from: )
> let sumSquaredOfResiduals = speeds.sumOfSquares
> 
> // grodiness deliberately enhanced for illustration
> 
> I’d rather not. The thing to be calculated is named at the bottom of the 
> paragraph. The intermediate steps must preserve names that change meaning 
> line-by-line. You have to study the code to recognize it as a single 
> arithmetic expression.
> 
> And by the by, if a vector operand is itself the result of a mutating 
> operation, the dependency graph becomes a nightmare to read — I can’t be sure 
> the illustration even expresses a plausible calculation.
> 
> Thinking 

Re: [swift-users] Why can't structs inherit from other structs?

2016-08-02 Thread Joe Groff via swift-users

> On Aug 1, 2016, at 5:28 PM, Rick Mann via swift-users  
> wrote:
> 
> It sure seems natural.
> 
> Is there some reason the language can't allow a sub-struct to add member 
> variables, such that the whole is treated like a contiguous set of members?

Class-style inheritance is tied to identity. Value types in Swift have no 
identity except for the value they contain, and they can be freely copied (or 
not) by the implementation. By adding fields to a struct, you change the value 
of that struct, and it doesn't make sense to say that a value with fewer fields 
"is-a" value with added fields. Those extra fields added by a sub-struct could 
be arbitrarily lost by copying (as often happens in C++ when copy constructors 
are invoked on inherited structs) and make defining equality difficult. Classes 
don't have these problems since each instance has a unique independent 
identity, and only references to that instance are passed around.

> In my case, I have a rect-like value type, but I'd rather it inherit from 
> CGRect, rather than contain a CGRect. That makes it much more natural to use.
> 
> Is allowing that just too complicated, or does it create type safety issues?

There is a different kind of inheritance that may make sense for value types. 
You can consider a type that can represent a proper subset (or the same set) of 
values from another type to be its subtype; for example, UInt8 could be a 
subtype of UInt16. If you have another rect-like type, which represents 
rectangles in a different way (perhaps using integer coordinates instead of 
Double, or using coordinate ranges instead of base + size), it might make sense 
for us to allow you to treat it as a subtype of CGRect for convenience.

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


Re: [swift-users] Draft guide for id-as-Any migration and known issues

2016-08-01 Thread Joe Groff via swift-users
I've also posted the document as a gist, to gather updates as I collect them:

https://gist.github.com/jckarter/5ffa9ba75050b94cd2cf9092b332a866

-Joe

> On Aug 1, 2016, at 11:46 AM, Joe Groff via swift-users 
> <swift-users@swift.org> wrote:
> 
> Hi everyone. SE-0116 should be landing in snapshots soon, which changes how 
> Objective-C APIs import into Swift. Instead of relying on special implicit 
> conversions to AnyObject, we now import the ObjC APIs using `Any` to get the 
> same effect without special language rules. I've written up a draft guide 
> about the kinds of changes necessary, along with some known issues. I'd also 
> like to gather feedback from anyone who's picked up the snapshot about their 
> experiences to make sure we address any pain points introduced by the 
> changes. Thank you for any feedback you can provide!
> 
> -Joe
> 
> ___
> 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] Cannot invoke 'stride' with an argument list of type '(from: Int, to: Int, by: Int)'

2016-07-05 Thread Joe Groff via swift-users
This is a known bug. The definition of 'stride' inside 'Int' for migration from 
Swift 2 causes the compiler to fail to find the global function. 
https://bugs.swift.org/browse/SR-1798

-Joe

> On Jul 4, 2016, at 8:41 PM, Adriano Ferreira via swift-users 
>  wrote:
> 
> Hi everyone!
> 
> I’m converting some code to Swift 3 and got this issue?
> 
> 
> 
> 
> 
> Does anybody know what’s going on?
> 
> Here’s the code, before and after conversion:
> 
> 
> // Swift 2.2
> extension Int {
> 
> // Repeat a block of code from `self` up to a limit
> func up(to upper: Int, by step: Int = 1, @noescape closure: () -> Void) {
> 
> for _ in self.stride(to: upper, by: step) {
> closure()
> }
> }
> }
> 
> // Swift 3
> extension Int {
> 
> // Repeat a block of code from `self` up to a limit
> func up(to upper: Int, by step: Int = 1, _ closure: @noescape () -> Void) 
> {
> 
> for _ in stride(from: self, to: upper, by: step) {
> closure()
> }
> }
> }
> 
> 
> // Usage
> 1.up(to: 10, by: 2) {
> print("Hi!")
> }
> 
> 
> Best,
> 
> — A
> ___
> 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] Checking whether an object is uniquely referenced, using a weak reference to it

2016-06-28 Thread Joe Groff via swift-users

> On Jun 28, 2016, at 9:32 AM, Jordan Rose via swift-users 
>  wrote:
> 
> 
>> On Jun 27, 2016, at 18:52, Tim Vermeulen  wrote:
>> 
>> Thanks for your reply. It didn’t clear up everything, though. The official 
>> documentation says "Weak references do not affect the result of this 
>> function.”, which suggests that weak (and unowned) references intentionally 
>> aren’t counted. The docs only mention the implementation of copy-on-write 
>> behaviour as a use case (which also happens to be what I’m using it for).
> 
> I would expect that weak references are important to count for COW, since you 
> can observe changes through them. Dave?

Passing a weak reference inout goes through a strong optional shadow copy. It 
wouldn't be safe to directly address the weak reference.

-Joe

>> 
>> Couldn’t there just a be a function that returns the reference count of a 
>> given object as an Int? It would make everything a lot easier (i.e. it 
>> wouldn’t need inout because it can just create a reference to that object, 
>> find the reference count, then subtract 1).
> 
> As we’ve said for a long time in Objective-C, asking for the reference count 
> of an object is meaningless. isUniquelyReferenced only works because it’s 
> conservative: because it only checks for “exactly 1”, it’s safe from 
> threading issues and autorelease pools. We do not plan to add a -retainCount 
> equivalent to Swift.
> 
> Jordan
> 
> ___
> 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] Hexadecimal floating-point literals

2016-06-27 Thread Joe Groff via swift-users

> On Jun 26, 2016, at 12:50 AM, Toni Suter via swift-users 
>  wrote:
> 
> Hi,
> 
> I have a question regarding hexadecimal floating-point literals. According to 
> the Lexical Structure 
> (https://developer.apple.com/library/prerelease/content/documentation/Swift/Conceptual/Swift_Programming_Language/LexicalStructure.html)
>  
> it is not possible to have a hex floating-point literal without the exponent. 
> At first I thought this makes sense.
> How else would the lexer / parser know if 0x123.beef is a hex floating-point 
> literal or a hex integer literal with a property 'beef'?
> However, if I define such a property on Int, it doesn’t work:
> 
> extension Int {
> var beef: Int {
> return 42
> }
> }
> 
> print(12.beef)// works
> print(0b1001.beef)// works
> print(0o77.beef)  // works
> print(0xabc.beef) // error: hexadecimal floating point literal must end 
> with an exponent
> 
> Is this just to avoid confusion for the programmer? Or is there some other 
> reason?

The lexer failed to backtrack if there wasn't a valid significand and exponent, 
but that was recently fixed, so this should work now. See 
https://github.com/apple/swift/pull/3124 .

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


Re: [swift-users] CGContext endPage method ambiguous (two candidates) Swift 3/Xcode 8

2016-06-17 Thread Joe Groff via swift-users

> On Jun 16, 2016, at 1:49 PM, Dave Reed via swift-users 
>  wrote:
> 
> I've got a project I had been working on using Swift2.2 and decided to 
> migrate to Swift3 (using Xcode 8 beta) before the project gets any bigger. I 
> successfully migrated everything except I have a CGContext for writing to a 
> PDF and calls the endPage() method. For that the compiler responds with 
> "ambiguous use of endPage()" and claims to find two candidates for it.
> 
> Is there a work around for this?

This came up in the WWDC labs this week too. One possible workaround is to wrap 
the original CGPDFContextEndPage function in your bridging header, then call 
the wrapper function from Swift.

-Joe

> I submitted it via bugreport.apple.com (# 26815976) but is there a better 
> place to report this?
> 
> Also, while the app won't be ready to release until after iOS 10 is released, 
> I would like to start TestFlight beta testing it before that. After doing the 
> conversion, I remembered that you can't submit builds with beta versions of 
> Xcode to the AppStore. Does this also apply to TestFlight betas? I hope not 
> given that Apple is strongly encouraging everyone to convert their code to 
> Swift 3, but I suspect that is the policy.
> 
> Thanks,
> Dave Reed
> 
> 
> ___
> 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] expression too complex

2016-06-16 Thread Joe Groff via swift-users

> On Jun 16, 2016, at 1:59 PM, davel...@mac.com wrote:
> 
> 
> Joe, 
> 
> I had an expression that worked fine with Swift2.2 but Swift3 (Xcode 8 
> version) complains it's too complex:
> 
> The variables are of type CGPoint and the function returns a Bool.
> 
>return (pt.x - p0.x) * (p1.y - p0.y) - (pt.y - p0.y) * (p1.x - p0.x) < 0.0

Thanks for letting us know. If you haven't yet, would you have time to file a 
bug report? cc'ing Joe Pamer in case he has any ideas here.

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


Re: [swift-users] inout params seem to have undefined behavior

2016-06-13 Thread Joe Groff via swift-users

> On Jun 13, 2016, at 1:39 PM, Jens Alfke <j...@mooseyard.com> wrote:
> 
> 
>> On Jun 13, 2016, at 9:45 AM, Joe Groff via swift-users 
>> <swift-users@swift.org> wrote:
>> 
>> It's not undefined behavior in that we try to ensure that memory safety is 
>> still preserved when inout parameters alias, but it is *unspecified* when 
>> updates to an inout parameter will be written back to the original argument.
> 
> But it seems that memory safety was broken in that an array assigned to a 
> ‘let’ variable was mutated. Doesn’t that violate the contract of its 
> immutability?

I see, missed that part. That's a bug—`acopy` should remain a distinct copy of 
`a`.

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


Re: [swift-users] Generic type metadata pattern not found?

2016-06-13 Thread Joe Groff via swift-users

> On Jun 11, 2016, at 5:24 PM, Jon Shier via swift-users 
>  wrote:
> 
> Swift Users:
>   In preparation for an upcoming iOS app project I’m trying out some new 
> project layout strategies. One of which is putting my network layer and 
> custom UI elements in frameworks separate from my main app. I’ve done this 
> with frameworks in my project, and then used CocoaPods to install the 
> dependencies for these frameworks (just the Networking framework at the 
> moment). However, I’m getting the following build error when the app tries to 
> link:
> 
> Undefined symbols for architecture x86_64:
>   "generic type metadata pattern for Alamofire.Response", referenced from:
>   type metadata accessor for 
> Alamofire.Response in 
> ViewController.o
> ld: symbol(s) not found for architecture x86_64
> clang: error: linker command failed with exit code 1 (use -v to see 
> invocation)
> 
> This occurs despite the Response type being visible to autocomplete in Xcode 
> and there being no compilation errors at build time. Is there anything I can 
> do to fix this or is this some sort of Xcode / Swift linker bug or 
> limitation? It seems like my options are to link Alamofire directly against 
> by app target or wrap the Response type in something of my own in my 
> Networking framework. I’d prefer not to have to import Alamofire directly, as 
> part of hiding all of the network stuff in a single framework was to limit 
> those sorts of dependencies.

This looks vaguely like an instance of some known bugs we have handling nested 
types. Do you have whole-module optimization enabled? Switching that on or off 
may move the problem around. Unnesting the type in the Alamofire source should 
work around the problem too.

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


Re: [swift-users] inout params seem to have undefined behavior

2016-06-13 Thread Joe Groff via swift-users

> On Jun 11, 2016, at 10:29 AM, Karl Pickett via swift-users 
>  wrote:
> 
> I don't believe the (spartan) docs address this case:
> 
> func foo(inout a: [Int], inout b: Int) {
>let acopy = a
>a = [4, 5, 6]
>print(acopy)  // prints "[1, 2, 3]"
>b = 99
>print(a)   // prints "[4, 5, 6]"
>print(acopy)  // prints "[1, 2, 99]" (e.g. a let variable changed!)
> }
> 
> var arr = [1,2,3]
> 
> foo(, b: [2])
> 
> print(arr)  // prints "[4, 5, 6]"
> 
> 
> Is this code "undefined", meaning the spec / doc doesn't specifically
> say what should be happening?  For instance, I can't believe a let
> variable gets changed.  The docs also say inout changes the original
> value when the function ends, not in the middle as is happening here.

It's not undefined behavior in that we try to ensure that memory safety is 
still preserved when inout parameters alias, but it is *unspecified* when 
updates to an inout parameter will be written back to the original argument. 
You should avoid aliasing inout parameters for this reason.

-Joe

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


Re: [swift-users] expression too complex

2016-06-06 Thread Joe Groff via swift-users

> On Jun 6, 2016, at 3:06 PM, G B via swift-users  wrote:
> 
> Is progress being made on the type checker to get the compiler to stop 
> whinging about the complexity of expressions?

Yes, a lot of cases work much better in Swift 3. You might give these a try in 
a nightly build. Please file a bug if you continue to see this in Swift 3 
though.

-Joe

> 
> I can’t really trim down the full project to isolate a good test case, but 
> I’m getting a compiler error on this line of code:
> let v=T.Vector4Type([axis[0]*s, axis[1]*s, axis[2]*s, cos(a/2.0)])
> 
> 
> Interestingly, this line compiled fine (everything is the same except the 
> last list element is moved to the front):
> let v=T.Vector4Type([cos(a/2.0), axis[0]*s, axis[1]*s, axis[2]*s])
> 
> 
> 
> The initializer that this code is embedded in is this:
> public init(axis:T.Vector3Type, angle a:T){
>let s=sin(a/2.0)
>let v=T.Vector4Type([axis[0]*s, axis[1]*s, axis[2]*s, cos(a/2.0)])
>let l=v.length()
>self.init(v/l)
> }
> 
> I’m running this in a playground, I don’t know if that makes a difference.
> 
> I’m willing to wait a little longer for the complier to do its job if it 
> means I don’t have to break my code down to one operation per line.
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

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


Re: [swift-users] Can't get Error pattern matching to work cross framework and command line tool

2016-06-01 Thread Joe Groff via swift-users
Thank you!

-Joe

> On May 31, 2016, at 9:49 PM, Joakim Hassila  wrote:
> 
> Hi Joe,
> 
> Absolutely, I just filed rdar://26569913 (used Radar according to community 
> guidelines of putting projects requiring Xcode to reproduce there).
> 
> I hope I captured the dependencies / reproduction steps properly in the 
> report, let me know if anything else is needed.
> 
> Cheers,
> 
> Joakim
> 
>> On 31 maj 2016, at 23:23, Joe Groff  wrote:
>> 
>> 
>>> On May 31, 2016, at 8:50 AM, Joakim Hassila via swift-users 
>>>  wrote:
>>> 
>>> Hi Ian,
>>> 
>>> Nope, it is the only definition - I also actually have tried to fully 
>>> qualify it as Z.Transaction.Error.NotFound without any difference both at 
>>> the throw and catch sides.
>>> 
>>> I do believe the compiler would have warned if the enum was ambigious 
>>> also...
>> 
>> Would you be able to file a bug with the project that displays this behavior?
>> 
>> -Joe
> 

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


Re: [swift-users] Can't get Error pattern matching to work cross framework and command line tool

2016-05-31 Thread Joe Groff via swift-users

> On May 31, 2016, at 8:50 AM, Joakim Hassila via swift-users 
>  wrote:
> 
> Hi Ian,
> 
> Nope, it is the only definition - I also actually have tried to fully qualify 
> it as Z.Transaction.Error.NotFound without any difference both at the throw 
> and catch sides.
> 
> I do believe the compiler would have warned if the enum was ambigious also...

Would you be able to file a bug with the project that displays this behavior?

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


Re: [swift-users] Swift closure memory problem

2016-05-27 Thread Joe Groff via swift-users

> On May 27, 2016, at 11:42 AM, Alon Muroch  wrote:
> 
> for example { () -> Void
> }

Can you please paste a complete example of code that triggers a leak, as text?

-Joe

> On Fri, May 27, 2016 at 7:59 PM, Joe Groff  wrote:
> 
> > On May 27, 2016, at 3:57 AM, Alon Muroch via swift-users 
> >  wrote:
> >
> > Hi everyone !
> > Its my first time writing here so i hope i could contribute.
> >
> > The following code seems to create a retain cycle that doesn't let 
> > SomeClass1 to release. Am i missing something ?
> >
> > 
> > ​​Alon.
> 
> What are you passing as `topClosure`?
> 
> -Joe
> 

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


Re: [swift-users] Swift closure memory problem

2016-05-27 Thread Joe Groff via swift-users

> On May 27, 2016, at 3:57 AM, Alon Muroch via swift-users 
>  wrote:
> 
> Hi everyone ! 
> Its my first time writing here so i hope i could contribute. 
> 
> The following code seems to create a retain cycle that doesn't let SomeClass1 
> to release. Am i missing something ?
> 
> 
> ​​Alon.

What are you passing as `topClosure`?

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


Re: [swift-users] Mapping C semantics to Swift

2016-05-19 Thread Joe Groff via swift-users

> On May 19, 2016, at 10:00 AM, Ken Burgett via swift-users 
>  wrote:
> 
> I would like to know if a struct in Swift has any guarantee of contiguity, 
> like a struct in C.  I am attempting to port a C program that makes many 
> assumptions about the underlying semantics of C structs, and does things like 
> overlaying an array over the struct using a cast, and then performs and 
> cryptographic hashing of the entire struct by treating it as an array.
> 
> 1.  I a Swift struct contiguous?
> 
> 2.  If 1 above is true, can I somehow cast an array over the struct?

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

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


Re: [swift-users] Default value for throwing closure argument of a rethrowing function

2016-05-16 Thread Joe Groff via swift-users

> On May 16, 2016, at 2:35 AM, bhargav gurlanka via swift-users 
>  wrote:
> 
> Hi all,
> 
> Could someone please tell me why the following fails?
> 
> func foo(f: () throws -> () = {}) rethrows {
> try f()
> }
> 
> // Fine
> foo({ })
> 
> // This fails with error:
> //call is to 'rethrows' function,
> //but a defaulted argument function can throw
> foo()
> 
> Why should I have to write "try foo()", shouldn't it take the default value 
> (non throwing closure)?

This looks like a bug. We'd appreciate a bug report on bugs.swift.org if you 
have some time.

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


Re: [swift-users] Range subscript is ambiguous

2016-05-16 Thread Joe Groff via swift-users

> On May 15, 2016, at 5:31 AM, Neil Faiman via swift-users 
>  wrote:
> 
> This function seems simple enough:
> 
> 
>func foo(a: [Int], n: Int) {
>var x : [Int] = a[0..}
> 
> But it doesn’t compile.
> 
>error: ambiguous subscript with base type '[Int]' and index type 
> 'Range'
>var x : [Int] = a[0..~^~~
>Swift.Array:100:12: note: found this candidate
>public subscript (subRange: Range) -> ArraySlice { get set }
>^
>Swift.MutableCollectionType:3:12: note: found this candidate
>public subscript (bounds: Range) -> MutableSlice { get 
> set }
>^
>Swift.CollectionType:2:12: note: found this candidate
>public subscript (bounds: Range) -> Slice { get }
>^
> 
> The oddity is that if I change the assignment to this
> 
>var y : [Int] = Array(a[0.. 
> then the compiler is happy.
> 
> Shouldn’t it be able to do any necessary type inference from the fact that 
> the expression is in a context where an array is required?

The error message is misleading (if you have time, we'd appreciate a bug 
report!). What's really going on is that a[0..

Re: [swift-users] Unexpected Optional unwrapping in generic fn

2016-05-16 Thread Joe Groff via swift-users

> On May 15, 2016, at 4:13 PM, Michael Gardner via swift-users 
>  wrote:
> 
> I'm having trouble understanding why the following code is trying to unwrap 
> an Optional.
> 
> 
> 
> class Proxy {
>   var value:T
>   init(_ value:T) {
>   self.value = value
>   }
> }
> 
> func setter(p:Proxy) -> Any? -> () {
>   return {p.value = $0 as! T}
> }
> 
> var i = Proxy(0), s = setter(i)
> 
> s(2)
> i.value // => 2
> s(nil) // => fatal error: unexpectedly found nil while unwrapping an Optional 
> value
> 
> 
> 
> My understanding is that since T is `Int?` here, the setter should be doing 
> (nil as! Int?), which doesn't cause an error. What am I missing?

You're right, it should be able to successfully cast a `nil` Any? to a nil 
`Int?. This is a bug. If you have time, could you write up a report on 
bugs.swift.org?

-Joe


> ___
> 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] Initializer inheritance doesn't work with generic class?

2016-05-16 Thread Joe Groff via swift-users
This is a known bug. I think Slava's currently working on fixing it.
> On May 15, 2016, at 2:41 PM, Neil Faiman via swift-users 
>  wrote:
> 
> Here is another, more blatant example of the failure to inherit initializers 
> from a generic base class:
> 
>class Concrete {
>init(value: Int) {}
>}
> 
>class ConcreteSub : Concrete {
>}
> 
>class Generic {
>init(value: T) {}
>}
> 
>class GenericSub : Generic {
>}
> 
>let concrete = ConcreteSub(value: 1)
>let generic = GenericSub(value: 1)
> 
> error: 'GenericSub' cannot be constructed because it has no accessible 
> initializers
>let generic = GenericSub(value: 1)
>  ^
> 
> ___
> 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] Conditional generic initializers?

2016-05-16 Thread Joe Groff via swift-users

> On May 15, 2016, at 11:55 AM, Neil Faiman via swift-users 
>  wrote:
> 
> Is this a relatively new language change? When I try it with the version of 
> Swift that comes with Xcode 7.3.1, I get
> 
>error: same-type requirement makes generic parameters 'T1' and 'T2' 
> equivalent
>extension Foo where T1 == T2 {
>   ^

Unfortunately, it's a limitation of our type system today that 
class/struct/enum extensions can't use '==' constraints. It can often be worked 
around by making a protocol instead.

-Joe

> 
>> On May 15, 2016, at 1:33 PM, Karl  wrote:
>> 
>> Yes. You need to put it in an extension.
>> 
>> extension Foo where T1 == T2 {
>>   convenience init(values: [T1]){
>>   ….
>>   }
>> }
>> 
>>> On 15 May 2016, at 14:45, Neil Faiman via swift-users 
>>>  wrote:
>>> 
>>> Is it possible for a generic class to have methods (specifically, 
>>> initializers) which are only defined if the generic parameters meet certain 
>>> constratins?
>>> 
>>> Here’s a concrete example:
>>> 
>>>  class Foo  {
>>>  init(pairs: [(T1, T2)]) {}
>>>  // What I’d like to be able to doL
>>>  convenience init "where T1 == T2" (values: [T1]) { self.init(pairs: 
>>> values.map{ ($0, $0) }) }
>>>  }
>>> 
>>> That is, I’d like to provide a convenience initializer that takes an array 
>>> of values instead of pairs, and turns the values into pairs, IF THE TWO 
>>> GENERIC TYPE PARAMETERS ARE THE SAME.
>>> 
>>> I can’t find a way to accomplish this. Is there one?
> 
> 
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

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


Re: [swift-users] String initializers and developer ergonomics

2016-05-09 Thread Joe Groff via swift-users

> On May 7, 2016, at 10:39 AM, Austin Zheng via swift-users 
>  wrote:
> 
> Hello Swift users,
> 
> I wanted to run something past you folks and get some opinions/feedback.
> 
> About a month ago on Hacker News I saw someone commenting about how Swift's 
> string-handling code was unbearably slow (3 seconds to run a code sample, vs. 
> 0.8 in Java). I asked him to provide the code, and he obliged. Unfortunately, 
> I didn't have time to dig into it until this morning. The code in its 
> entirety can be found here: 
> https://gist.github.com/austinzheng/d6c674780a58cb63832c4df3f809e683
> 
> At line 26 we have the following code:
> 
> result.append(begin == eos ? "" : String(cs[begin.. 
> 'cs' is a UTF16 view into an input string, while 'result' is a [String]. When 
> I profiled the code in Instruments, I noticed that it was spending 
> significant time within the reflection machinery.
> 
> It turns out that the initializer to make a String out of a utf16 view looks 
> like this, and I believe this is the initializer the author intended to call:
> 
> init?(_: String.UTF16View)
> 
> However, the actual initializer being called was this String initializer in 
> the Mirror code:
> 
> public init(_ instance: Subject)
> 
> This seems like a tricky gotcha for developers who aren't extremely familiar 
> with both the String and reflection APIs. His code looked reasonable at a 
> first glance and I didn't suspect anything was wrong until I profiled it. 
> Even so, I only made the connection because I recognized the name of the 
> standard library function from poking around inside the source files.
> 
> What do other people think? Is this something worth worrying about, or is it 
> so rare that it shouldn't matter? Also, any suggestions as to how that code 
> sample might be improved would be appreciated - my naive first attempt wasn't 
> any better.

This definitely strikes me as a problem. The String(_:) constructor is very 
easy to call by accident if you're trying to hit another unlabeled initializer. 
It also strikes me as not particularly "value-preserving", since stringifying 
many types loses information. Perhaps we should propose giving it a label, 
String(printing:) maybe?

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


  1   2   >