Using Swift Code inside of a Nativescript Plugin - swift

I'm new to Nativescript and Swift and I'm trying to use one of Nativescript's most useful feature. The Ability to use Swift/Objective C code directly inside of your Typescript code.
So in my plugin I have this swift File: /ios/src/TestClass.swift
open class TestClass {
#objc public func testTestClass() {
return "It Works!"
}
}
but when I try to generate type information for this class using ns typings ios, No types are generated for this class.
I've also tried annotating the class with #objc(TestClass) and still the same result.
I have some cocapod libraries for which types are being generated.
Is it possible in Nativescript to use Swift files directly? or have I misunderstood the documentation?.
Edit: Turning the package into a coca pod makes everything work.

Related

Swift public func not being exported from framework

I created a Swift Framework project in Xcode and I'm trying to export a function for Unity to call. I defined the function like this.
#_cdecl("showPaymentForm")
public func showPaymentSheet()-> PKPaymentAuthorizationViewController?{
NSLog("In showPaymentForm - Navtive code.")
return ApplePayLib.showPaymentSheet(label: "something", total: 9.99, mainViewController: nil)
I ran
nm -gU
against the binary and it doesn't show any functions exported called showPaymentForm. I check the "Symbols Hidden by Default" to make sure it was set to "No".
If I do the same as above in a package instead of a framework, it works fine. I didn't stick with the package project because I need to include other packages that didn't play nice with it.
Not really sure what else to check.
It turned out the issue was due to the swift file not having a target selected. Once I selected the correct target, the function as exported correctly.

VS Code with Volar extension shows error, but Vue3 app is working as expected

I started a small side project (homage to the classic Snake game) today and everything is working fine, but VS Code shows two errors in a Vue component and it seems it is using an outdated version of imported classes and components.
Initially I started with a class, but later I added an interface that really only exposes public properties (through getter and setter) and methods. But the component using this class still thinks the class is required as a paramter and complains that the private properties are not available on the type.
I am not sure if the error comes from VS Code itself or the Volar extension which is recommended for Vue3 and Typescript.
The code is available as a public github repo: https://github.com/onyx-blackbird/vue-snake/blob/master/src/components/GameGrid.vue
The lines that are red are: #23 and #122 at the time of writing. If I update the file in the meantime here the two lines (in both cases snake is of ISnake and the method and component both expect ISnake):
const { food, placeFood } = useFood(maxX, maxY, snake);
<SnakeFigure :snake="snake" :is-game-over="isGameOver"></SnakeFigure>
Here the referenced class and interface:
https://github.com/onyx-blackbird/vue-snake/blob/master/src/model/Snake.ts
It might be that you have 2 plugins enabled at the same time - volar and vetur. Vetur must be turned off.

Dart Package - How to hide internal methods and classes?

I am developing a package for Flutter Apps
There are methods and classes that are useful only for the package itself, and not for the programmer who will import my package, is possible to hide this methods and classes for further implementation?
Example:
DataService.dart
export class DataService{
//Must be visible only for my library
static notifyDataChanged(InternalEvent internalEvent){ ... }
//Must be visible for anyone
static addCallbackOnDataChange(onDataChangeCallback) { ... }
}
InternalEvent.dart
//Must be visible only for my library as well
export class InternalEvent {
...
}
The usual approach to having package-only declarations is to put them in a library in the lib/src/ directory, and not export that library. The other libraries in the package can import the package-only library, but users outside the package are discouraged from importing libraries in lib/src/ directly. (It's not impossible, just something that's discouraged because the package is free to change those libraries without warning).
If the package-only features require access to library private parts of public classes, then they need to be in the same library. The traditional way is then to declare both in a library in lib/src/ and export only the parts of that library which needs to be public:
library myPackage;
export "src/allDeclarations.dart" hide Private, Declarations;
// or, preferably,
export "src/allDeclarations.dart" show Public, Things;
Generally you should only put exported and non-exported declarations in the same library if absolutely necessary. Otherwise the hide/show lists become too cumbersome and it's to easy to forget a declaration in a hide list.
You have a few possibilities:
Making a method/variable private, by prefixing it with _:
class _InternalEvent {}
Use the hide/show directives:
// lib/src/event.dart
class InternalEvent {}
class VisibleEvent {}
// lib/my_package.dart
export 'src/event.dart' hide InternalEvent;
OR
export 'src/event.dart' show VisibleEvent;
For package-private members exists an annotation, #internal.
Using #internal the analyzer emit a warning when:
you export the annotated element (from a file under lib)
a consumer of your package imports the annotated element
Anyway, Dart seems to me to make things really complicated. The need to have members who are neither completely public nor inaccessible from outside the file is elementary, yet no solution provides certainties.
Note that:
the doc says to keep the package-private elements in files under lib/src, yet the consumers of your package will still be able to import them, without even the analyzer producing a warning; it's just a convection;
using the #internal annotation, the analyzer (ie the ide, which rely on the analyzer) produces a warning, but nothing prevents you from compiling the code anyway. The situation improves a little if you increase the severity level of the warning produced by the analyzer when the annotation is not respected. To do this, you need to create an analysis_options.dart file like the following:
analyzer:
errors:
invalid_use_of_internal_member: error #possible values: ignore, info, warning, error
Note that the #internal annotation, like other similar ones (#visibleForTesting, #protected) is part of the meta package, which is included in the Flutter Sdk, but which must be included as a dependency in pure-dart packages.
its so simple
suppose i have a below code in src folder of your lib,
class myClass1 {}
class myClass2 {}
class myClass3 {}
below export statement will make all 3 classes visible/accesible
export 'src/mylib_base.dart' ;
below export statement will make myClass3 visible/accessible and remaining not accessible
export 'src/mylib_base.dart' show myClass3 ;
below export statement will make myClass3 not visible/accessible and remaining accessible
export 'src/mylib_base.dart' hide myClass3 ;
So simply
with hide classes/function ,hide those that you mention and remaining will be shown to end user
with show classes/function ,show those that you mention and remaining will be hide to end user

Swift extensions that apply only when you import them

I have some swift extensions I want to across projects.
I'd like to avoid category pollution though, unless those extensions are requested.
Is it possible to write them so that they only apply if I've done a certain import, like:
import MySwiftExtensions
// Use custom extensions
let x = [1,3,5,7].average()
let y = [1,3,5,7].firstWhere { $0 > 3 }
let z = "campervan".make1337()
I could write these as static methods wrapped in a single letter class (eg: ø.average([1,3,5,7]), like lodash) to achieve the same thing but sometimes you get much more concise usage from instance methods.
You wrote:
I have some swift extensions I want to across projects...
When I have code that I want to use across projects I create a separate framework to hold that code. Then, when I want to use that code in a new project, I embed the framework in that project. Or, for development purposes, I create a workspace that includes the project and the framework. That allows me to work on both at the same time, and then only embed the framework in the final product when it is time to export it.
Once the framework is either embedded or in the same workspace, then you should be able to import it into any individual file in your project with:
import MySwiftExtensions
Any file that does not have the import statement will not have access to the extensions.
EDIT:
Here is a link to a blog that describes how to create a Cocoa Touch Framework. And here is another link that describes in detail how to use workspaces to use frameworks in development projects.
I would like to focus attention on what you reported: "..only apply if I've done a certain import.."
It would also mean you want these extensions can be applyed only to a specific class
As reported in this interesting Apple blog chapter and in the official Apple doc you can handle the "Access Control" of your extension
You can extend a class, structure, or enumeration in any access
context in which the class, structure, or enumeration is available.
Any type members added in an extension have the same default access
level as type members declared in the original type being extended. If
you extend a public or internal type, any new type members you add
will have a default access level of internal. If you extend a private
type, any new type members you add will have a default access level of
private.
Alternatively, you can mark an extension with an explicit access level
modifier (for example, private extension) to set a new default access
level for all members defined within the extension. This new default
can still be overridden within the extension for individual type
members.
/* no access level modifier: default access level will be 'internal' */
extension UIViewSubClass
{
// default access level used: internal
var helloWorld : String {
get {
return "helloWorld"
}
}
}
// modify default access level to public
public extension UIViewSubClass
{
// default access level used: public
var helloWorld : String {
get {
return "helloWorld"
}
}
}
The members of extensions marked private are available within the file where they’re defined, and are not available outside that file. Outside the file where the private extension members were defined, any attempt to use them results in an error, and auto-complete wouldn’t even list them
// modify default access level to private
private extension UIViewSubClass
{
var helloWorld : String {
get {
return "helloWorld"
}
}
}
I don't believe you can do what you want per se, but I've used the following approach to provide functionality to only the specific class that implements an interface:
protocol ExampleProtocol {
}
extension ExampleProtocol where Self: UIViewController{
// extend what you need to here
}

Importing classes from playground page into another page

Note: This is a different question than importing generic swift files (which can be done using the Sources folder).
I have a playground with 2 pages and I would like to use a protocol defined in the first page in the second page. I'll use an example of JSON conversion.
JSON.xcplaygroundpage
import Foundation
protocol JSONConvertible {
func jsonValue() -> String
}
JSONArray.xcplaygroundpage
import Foundation
//Undeclared type JSONConvertible
extension Array : JSONConvertible {
}
I have tried the following imports:
import MyPlayground
import MyPlayground.JSON
import JSON
import JSON.Contents (in finder the file name is actually Contents.swift)
I have also tried adding JSON.xcplaygroundpage into the Source folder of JSONArray as well as the Resources folder.
Note: I realize that I could put the protocol definition in a separate JSON.swift and include that in my project Sources folder. That doesn't really answer my question.
This is working in Xcode 8.3.3.
For code common to multiple pages, put it in separate files under top-level Sources group. Be sure to have proper Swift access control keywords in the right places.
Note from http://help.apple.com/xcode/mac/8.2/#/devfa5bea3af:
...the auxiliary Swift source file must export it using the public keyword. This includes classes, methods, functions, variables, and protocols.
Common.swift:
public class DoIExist { public init(){ print("Woot!")} }
Then you can reference it in all of the other pages. Like this:
Page2:
//: [Previous](#previous)
let d = DoIExist()
//: [Next](#next)
You can see that it works because of the console output ("Woot!") and the view results gutter.
To achieve this, I followed the directions at the Apple Xcode documentation about Playgrounds. When Apple inevitably moves those docs and does not provide a forwarding link, read on for how I found it.
I searched for the clues found in the link in cocoapriest's answer: "ios recipes Playground Help Add Auxilliary Code to a Playground". This leads to a document Apple is currently calling "Xcode Help" in a chapter titled "Use playgrounds" in a section titled "Add auxiliary code to a playground".
Just got this to work with this instruction by Apple: https://developer.apple.com/library/ios/recipes/Playground_Help/Chapters/AddAuxilliaryCodetoaPlayground.html
Make sure to declare your classes are public. Also, I had to re-start the Xcode to take the effect.