Swift 2: expression is ambiguous? - swift2

The following code used to work before I migrated to Swift 2 now I can't seem to work around it:
let cal = NSCalendar(calendarIdentifier: GregorianCalendar)
let components = cal!.components(.CalendarUnitDay | .CalendarUnitMonth | .CalendarUnitYear, fromDate: date) **error at this line**
let newDate = cal!.dateFromComponents(components)
I'm getting the following error message:
Type of expression is ambiguous without more context

In Swift 2 there is a change in the declaration of NSCalendarUnit as well as in the handling of OptionSetType
let cal = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)
let components = cal!.components([.Day, .Month, .Year], fromDate: date)
Please folks read the Swift Blog and the current Swift Language Guide

I was able to fix the error by force typecasting
let components = calendar.components([.Hour, .Minute, .Second], fromDate: date as! NSDate)

Related

F# Type Provider slows down intellisense in Visual Studio 2017

I have a very simple type provider; all types are erased, the provided type has 2000 int readonly properties Tag1..Tag2000
let ns = "MyNamespace"
let asm = Assembly.GetExecutingAssembly()
let private newProperty t name getter isStatic = ProvidedProperty(name, t, getter, isStatic = isStatic)
let private newStaticProperty t name getter = newProperty t name (fun _ -> getter) true
let private newInstanceProperty t name getter = newProperty t name (fun _ -> getter) false
let private addStaticProperty t name getter (``type``:ProvidedTypeDefinition) = ``type``.AddMember (newStaticProperty t name getter); ``type``
let private addInstanceProperty t name getter (``type``:ProvidedTypeDefinition) = ``type``.AddMember (newInstanceProperty t name getter); ``type``
[<TypeProvider>]
type TypeProvider(config : TypeProviderConfig) as this =
inherit TypeProviderForNamespaces(config)
let provider = ProvidedTypeDefinition(asm, ns, "Provider", Some typeof<obj>, hideObjectMethods = true)
let tags = ProvidedTypeDefinition(asm, ns, "Tags", Some typeof<obj>, hideObjectMethods = true)
do [1..2000] |> Seq.iter (fun i -> addInstanceProperty typeof<int> (sprintf "Tag%d" i) <## i ##> tags |> ignore)
do provider.DefineStaticParameters([ProvidedStaticParameter("Host", typeof<string>)], fun name args ->
let provided = ProvidedTypeDefinition(asm, ns, name, Some typeof<obj>, hideObjectMethods = true)
addStaticProperty tags "Tags" <## obj() ##> provided |> ignore
provided
)
do this.AddNamespace(ns, [provider; tags])
Then a test project with two modules in separate files:
module Common
open MyNamespace
type Provided = Provider<"">
let providedTags = Provided.Tags
type LocalTags() =
member this.Tag1 with get() : int = 1
member this.Tag2 with get() : int = 2
.
.
member this.Tag1999 with get() : int = 1999
member this.Tag2000 with get() : int = 2000
let localTags = LocalTags()
module Tests
open Common
open Xunit
[<Fact>]
let ProvidedTagsTest () =
Assert.Equal<int>(providedTags.Tag1001, 1001)
[<Fact>]
let LocalTagsTest () =
Assert.Equal<int>(localTags.Tag100, 100)
Everything works as expected (tests execution included). The problem I have is with the design time behavior inside Visual Studio, while I write code. I expect to have some overhead due to the type provider, but the slowness seems frankly excessive. The times reported below are in seconds and refer to the time measured from pushing the dot (.) key until the intellisense property list appears on the screen
providedTags. -> 15
localTags. -> 5
If I comment out or remove the first test code lines (so to eliminate any references to the provided stuff), then I get
localTags. -> immediate
If the number of properties is greater, the time seems to increase exponentially, not linearly, so that at 10000 it becomes minutes.
Questions are:
Is this normal or am I doing something wrong?
Are there guidelines to achieve a faster response?
If someone is curious about why I need so many properties, I am trying to supply an instrument to data analysts so that they can write F# scripts and get data out of an historian database with more than 10000 tags in its schema.
Issue has been fixed by Don Syme, see
https://github.com/fsprojects/FSharp.TypeProviders.SDK/issues/220
and
https://github.com/fsprojects/FSharp.TypeProviders.SDK/pull/229

Xcode - Swift 4 Encoding error

I have this code :
let data = "NgAzADYANQA1ADEANwA0ADgANQA1ADQANgA4ADgAMAA0ADcALwAvAGIAYQAwAGQAZABlAGQANAAtAGYANAAzAGUALQA0ADAANABkAC0AYQAzAGYAYgAtADQAZQA2ADIAZQBhADkAMgBiADMAYgBiAA=="
let dataDecoded = Data(base64Encoded: data, options: NSData.Base64DecodingOptions.ignoreUnknownCharacters)!
let decodedString = String(decoding: dataDecoded, as: UTF8.self)
print(decodedString)
On my output window, i have this result :
636551748554688047//ba0dded4-f43e-404d-a3fb-4e62ea92b3bb
But on my variable, i have :
6\03\06\05\05\01\07\04\08\05\05\04\06\08\08\00\04\07\0/\0/\0b\0a\00\0d\0d\0e\0d\04\0-\0f\04\03\0e\0-\04\00\04\0d\0-\0a\03\0f\0b\0-\04\0e\06\02\0e\0a\09\02\0b\03\0b\0b\0
please help me :)
Seems your input data is not int UTF-8, try this:
let decodedString = String(data: dataDecoded, encoding: .utf16LittleEndian)

DateTimeFormatterBuilder parsing days below 31 SMART not STRICT if appendValueReduced is used

Playing in groovyConsole with DateTimeFormatter and DateTimeFormatterBuilder
String inputDateString = "31.2.58" // german date format
dtfIn = DateTimeFormatter
.ofPattern ( "d.M.uu" )
.withResolverStyle ( ResolverStyle.STRICT )
dtfIn.parse(inputDateString) // ERROR as expected
...but
// with base range 1937-2034
dtfIn = new DateTimeFormatterBuilder()
.appendPattern("d.M.")
.appendValueReduced(ChronoField.YEAR, 2, 2, Year.now().getValue() - 80)
.parseStrict()
.toFormatter()
dtfIn.parse(inputDateString) // Result: 1958-02-28
So DateTimeFormatterBuilder with .parseStrict() would parse rather SMART, which DateTimeFormatterBuilder shouldn't do at all but either STRICT or LENIENT (?)'
With day numbers over 31 I'll get an error.
The problem seem to be .appendValueReduced(). Without it I'd become an error as expected.
What do I do wrong?
Thanks
Rawi
DateTimeFormatter from DateTimeFormatterBuilder.toFormatter() is indeed SMART as documented:
The resolver style will be SMART
To obtain STRICT one has to use DateFormatter.withResolverStyle(ResolverStyle)
in this case as follows:
.toFormatter().withResolverStyle(ResolverStyle.STRICT);

Convert SQL Statement to Predicate or NSExpression

I am facing a problem with converting below SQL to NSExpression
SELECT id,trait1,trait2,trait3,sum(trait1+trait2+trait3) as total FROM `bookings` GROUP BY id order by total desc
Below is my code in this code I am only able to add the two key values not three key values.
func aggregateProductsInContext(context:NSManagedObjectContext) {
var expressionDescriptions = [AnyObject]()
expressionDescriptions.append("name")
let expressionDescription = NSExpressionDescription()
expressionDescription.name = "Sold"
let exp1 = NSExpression(forKeyPath: "trait1")
let exp3 = NSExpression(forKeyPath: "trait2")
let exp3 = NSExpression(forKeyPath: "trait3")
let stas = NSExpression(forFunction:"add:to:", arguments:[exp1,exp3])
expressionDescription.expression = stas
expressionDescription.expressionResultType = .Integer64AttributeType
expressionDescriptions.append(expressionDescription)
let request = NSFetchRequest(entityName: "booking")
request.propertiesToGroupBy = ["name"]
request.resultType = .DictionaryResultType
request.sortDescriptors = [NSSortDescriptor(key: "name", ascending: true)]
request.propertiesToFetch = expressionDescriptions
var results:[[String:AnyObject]]?
do {
results = try context.executeFetchRequest(request) as? [[String:AnyObject]]
} catch _ {
results = nil
}
print(results)
}
Please find the attached images of actual table values and resulted values for reference.
Thanks!
My Solution:
I am able to solve my problem by doing this
let ec = NSExpression(forFunction:"add:to:", arguments:[exp1,exp2])
let ec1 = NSExpression(forFunction:"add:to:", arguments:[ec,exp3])
let ec2 = NSExpression(forFunction:"add:to:", arguments:[ec1,exp4])
let ec3 = NSExpression(forFunction:"add:to:", arguments:[ec2,exp5])
If there is any other way to achieve this, please let me know
Thanks!
Here is the solution which I had implemented and it's work fine.
let ec = NSExpression(forFunction:"add:to:", arguments:[exp1,exp2])
let ec1 = NSExpression(forFunction:"add:to:", arguments:[ec,exp3])
let ec2 = NSExpression(forFunction:"add:to:", arguments:[ec1,exp4])
let ec3 = NSExpression(forFunction:"add:to:", arguments:[ec2,exp5])
But I am sure there must be some other good way to do that. If any one have any other solution. please let me know.
Thanks!

Swift 2 - kCTForegroundColorAttributeName

let nameAttributes = [NSFontAttributeName:nameFont, kCTForegroundColorAttributeName:UIColor.whiteColor().CGColor] as [String:AnyObject]
var nameAttributedString = NSMutableAttributedString(string:name, attributes:nameAttributes)
I have these values which are working on Swift 1.2. But on Swift 2, they don't work.
I receive an error on first line:
'_' is not convertible to 'CFString'
And the problem is kCTForegroundColorAttributeName. Without kCTForegroundColorAttributeName, it would works. But I need it to change the color..
In addition:
kCTForegroundColorAttributeName:UIColor.whiteColor().colorWithAlphaComponent(0.7).CGColor
gives me an error:
'_' is not convertible to 'CGFloat'
In Swift 2, attributes on NSMutableAttributedString has to be [String:AnyObject] while in Swift 1.2 was [NSObject:AnyObject].
Any ideas ?
Why not just use NSForegroundColorAttributeName?
Use this Code
let attrs2 = [NSFontAttributeName : FontWithBook(10),NSForegroundColorAttributeName :UIColor.grayColor()]
var gString = NSMutableAttributedString(string:"(Mandatory)", attributes:attrs2)

Resources