Swift 2.0 / Xcode 7B5 - Classes can only be found if put in a certain file - xcode

I noticed that at a given point the class User could not be found when I wanted to use it in other classes. Nothing suspicious about it. At a given point I started to experiment with what place I put the code.
If I put all these classes together in one of my older files, all compiles. If I put them all together in a newer file, the other parts of my code consuming these classes do not compile. If I rename a file (from User.swift to AUser.Swift for example) nothing changes, meaning what compiles keeps compiling and what doesn't compile still doesn't compile based on name. It really seems to be the age of the file or something like that.
It appears as if everything I add later related to this particular cluster of classes will not compile in a newer file. These files are included when building, I checked that. There is nothing strange about the code I think:
import UIKit
public class User: AddressBookContact {
var home: Home?
var friends = [Friend]()
}
public class Friend: AddressBookContact {
}
class Session: NSObject {
private static let instance = Session()
override private init() {
super.init()
}
class func sharedInstance() -> Session {
return instance
}
static var loggedInUser: User?
}

Look in the File Inspector Utility pane (the right-hand pane). The file in question likely is not a member of the target.

Related

How to import a class from a Jenkins Shared Library into the pipeline

I was using some global methods in the /var directory of the shared library, and everything worked fine. Now I need to keep the state of the process, so I'm writting a groovy class.
Basically I have a class called 'ClassTest.groovy' in '/src' which is something like this;
class ClassTest {
String testString
def method1() { ... }
def method2() { ... }
}
and at the begining of the pipeline
library 'testlibrary#'
import ClassTest
with result:
WorkflowScript: 2: unable to resolve class ClassTest #line 2, column 1.
import ClassTest
before, I was just goind
library 'testlibrary#' _
and using the methods as
script {
libraryTest.method1()
...
libraryTest.method2()
}
where the methods were in a file '/var/libraryTest.groovy' and everything worked. So I know that the shared library is there, but I'm confused with the way groovy / Jenkins handle classes / shared libraries.
What's the correct way to import a class? I cannot find a simple example (with groovy file, file structure and pipeline) in the documentation.
EDIT:
I moved the file to 'src/com/company/ClassTest.groovy' and modified the pipeline as
#Library('testlibrary#') import com.company.ClassTest
def notification = new ClassTest()
but now the error is
unexpected token: package # line 2
the first two lines of the groovy file are:
// src/com/company/ClassTest.groovy
package com.company;
So far this is what I've found.
To load the library in the pipeline I used:
#Library('testlibrary#') import com.company.ClassTest
def notification = new ClassTest()
In the class file, no package instruction. I guess that I don't need one because I don't have any other files or classes, so I don't really need a package. Also, I got an error when using the same name for the class and for the file where the class is. The error specifically complained and asked for one of them to be changed. I guess this two things are related to Jenkins.
That works, and the library is loaded.
(Maybe it can help someone else)
I was having the same issue.
Once I added a package-info.java inside the folder com/lib/, containing
/**
* com.lib package
*/
package com.lib;
and adding package com.lib at the first line of each file, it started to work.
I had the same problem.
After some trial and error with the docs of Jenkins.(https://www.jenkins.io/doc/book/pipeline/shared-libraries/#using-libraries)
I found that when I wanted to import a class from the shared library I have, I needed to do it like this:
//thanks to '_', the classes are imported automatically.
// MUST have the '#' at the beginning, other wise it will not work.
#Library('my-shared-library#BRANCH') _
// only by calling them you can tell if they exist or not.
def exampleObject = new example.GlobalVars()
// then call methods or attributes from the class.
exampleObject.runExample()

Extension of a nested type in Swift

I have a main class, also providing a namespace:
class A {
}
and a nested class added via an extension (all for the sake of using separate files):
extension A {
class B {
}
}
I want to add functionality to the nested class (B) by extending it; I've tried:
extension A.B {
}
I get "'B' is not a member type of 'A'".
(I've also tried some less reasonable things but I will omit them here to avoid embarrassment. Reading Swift docs and Googling for "swift nested class extension" have not yielded an answer either.)
Any idea if and how that could be accomplished?
UPDATE:
This code works as expected when in a single file (or in a Playground), thanks to user3441734 for trying it out!
Still does not work when the 3 parts are in separate files, perhaps a bug in current implementation of the Swift compiler. I will submit a bug report to Apple.
It seems like this problem is related to SR-631. I've encountered similar a issue, I guess the complier is trying to process the file where you extend the nested class before the one where it's defined. Therefore you have this error saying that that A has no member B.
The solution I've found is to go to your target settings, open Build Phases.
There, in Compile Sources section you should put the file where you define the nested class above files where you extend it.
Update
The fix will be shipping with Xcode 10.2
this works in my playground, as expected
class A {
}
extension A {
class B {
}
}
extension A.B {
func foo() {
print("print from extension A.B")
}
}
let ab = A.B()
ab.foo() // print from extension A.B

Can I Write a Spotlight Importer in Swift?

I need to write a Spotlight Importer for an application that I've written in Swift, and am referring to the official Apple guide for Writing a Spotlight Importer.
It seems straightforward enough, however creating a Spotlight Importer project creates a default setup for an Objective-C implementation. Now, working with Objective-C isn't a huge problem (I've used it plenty of times in the past) but everything I've written for my application is in Swift, so I'd really I'd like to write the importer in Swift too to avoid switching between languages, and also so I can share some of the code that I've already done for reading/writing files.
Firstly, is it possible to write a Spotlight Importer using Swift instead of Objective-C? And if it is, where should I start (e.g- if I take the Objective-C starting point, what would I do to switch over to Swift instead)?
It took me a bit of time to get this to work.
Instead of adding Swift code to the mdimporter, I import an embedded framework already setup for my app.
I removed all the example code except main.c and GetMetadataForFile.m.
In the latter I import my framework where all the functionality now resides as Swift code.
The built mdimporter is added to the app.
In the File Inspector set Location to Relative to Build Products.
The app then adds the mdimporter with a Copy Files Build Phase.
Destination: Wrapper
Subpath: Contents/Library/Spotlight
The following needs to be added to the Run Search Paths build setting, as we are linking to the app's embedded frameworks.
#loader_path/../../../../../Frameworks
If you get compiler error that the framework module can't be found when building the app, depending on how your workspace is set up, you might need to modify your app's Scheme.
Turn off Parallelize Build
Add the Build targets in this sequence:
Frameworks project(s)
mdimporter project
App project
The additional benefit of having all the logic in a framework, is that it can be prototyped and verified in a Playground. A million times easier than debugging an mdimporter plugin.
Yes, it is possible to write a Spotlight Importer entirely* in Swift!
*except for a few lines of code in main.m
I've just published one here: https://github.com/foxglove/MCAPSpotlightImporter
Here's a detailed blog post about the implementation process:
https://foxglove.dev/blog/implementing-a-macos-search-plugin-for-robotics-data
The difficult part of this is implementing a plugin that's compatible with the CFPlugIn architecture. (The MDImporter-specific logic is relatively minimal.) The CFPlugIn API is based on Microsoft's COM and Apple's docs are almost 20 years old.
The plugin is expected to be a block of memory conforming to a certain memory layout — specifically, the first value in the block must be a pointer to a virtual function table (vtable) for the requested interface (in the case of a MDImporter, this is either MDImporterInterfaceStruct or MDImporterURLInterfaceStruct) or the base IUnknown interface. This layout is documented here.
I wanted to organize the Swift code into a class, but you can't control the memory layout of a Swift class instance. So I created a "wrapper" block of memory which holds the vtable and an unsafe pointer to the class instance. The class has a static func allocate() which uses UnsafeMutablePointer to allocate the wrapper block, create and store the class instance in it, and also initialize the vtable.
The vtable implements the standard COM base interface (IUnknown) functions (QueryInterface, AddRef, and Release) by grabbing the class instance out of the wrapper and calling the queryInterface(), addRef(), and release() methods on the instance. It also implements the Spotlight-specific ImporterImportURLData function (or ImporterImportData). Unfortunately, in my testing, it seemed like Spotlight did not pass the correct pointer to the wrapper struct as the first argument to ImporterImportURLData, so it was impossible to call a method on the class instance, so the function that actually imports attributes for a file had to be a global function. For this reason I wasn't able to make the plug-in implementation a more generic class that could be used with any interface — it has to be tied to a specific global importer function.
I'd encourage you to view the full source on GitHub, but in the interest of not being a link-only answer, here's the core functionality:
final class ImporterPlugin {
typealias VTable = MDImporterURLInterfaceStruct
typealias Wrapper = (vtablePtr: UnsafeMutablePointer<VTable>, instance: UnsafeMutableRawPointer)
let wrapperPtr: UnsafeMutablePointer<Wrapper>
var refCount = 1
let factoryUUID: CFUUID
private init(wrapperPtr: UnsafeMutablePointer<Wrapper>, factoryUUID: CFUUID) {
self.wrapperPtr = wrapperPtr
self.factoryUUID = factoryUUID
CFPlugInAddInstanceForFactory(factoryUUID)
}
deinit {
let uuid = UUID(factoryUUID)
CFPlugInRemoveInstanceForFactory(factoryUUID)
}
static func fromWrapper(_ plugin: UnsafeMutableRawPointer?) -> Self? {
if let wrapper = plugin?.assumingMemoryBound(to: Wrapper.self) {
return Unmanaged<Self>.fromOpaque(wrapper.pointee.instance).takeUnretainedValue()
}
return nil
}
func queryInterface(uuid: UUID) -> UnsafeMutablePointer<Wrapper>? {
if uuid == kMDImporterURLInterfaceID || uuid == IUnknownUUID {
addRef()
return wrapperPtr
}
return nil
}
func addRef() {
precondition(refCount > 0)
refCount += 1
}
func release() {
precondition(refCount > 0)
refCount -= 1
if refCount == 0 {
Unmanaged<ImporterPlugin>.fromOpaque(wrapperPtr.pointee.instance).release()
wrapperPtr.pointee.vtablePtr.deinitialize(count: 1)
wrapperPtr.pointee.vtablePtr.deallocate()
wrapperPtr.deinitialize(count: 1)
wrapperPtr.deallocate()
}
}
static func allocate(factoryUUID: CFUUID) -> Self {
let wrapperPtr = UnsafeMutablePointer<Wrapper>.allocate(capacity: 1)
let vtablePtr = UnsafeMutablePointer<VTable>.allocate(capacity: 1)
let instance = Self(wrapperPtr: wrapperPtr, factoryUUID: factoryUUID)
let unmanaged = Unmanaged.passRetained(instance)
vtablePtr.initialize(to: VTable(
_reserved: nil,
QueryInterface: { wrapper, iid, outInterface in
if let instance = ImporterPlugin.fromWrapper(wrapper) {
if let interface = instance.queryInterface(uuid: UUID(iid)) {
outInterface?.pointee = UnsafeMutableRawPointer(interface)
return S_OK
}
}
outInterface?.pointee = nil
return HRESULT(bitPattern: 0x8000_0004) // E_NOINTERFACE <https://github.com/apple/swift/issues/61851>
},
AddRef: { wrapper in
if let instance = ImporterPlugin.fromWrapper(wrapper) {
instance.addRef()
}
return 0 // optional
},
Release: { wrapper in
if let instance = ImporterPlugin.fromWrapper(wrapper) {
instance.release()
}
return 0 // optional
},
ImporterImportURLData: { _, mutableAttributes, contentTypeUTI, url in
// Note: in practice, the first argument `wrapper` has the wrong value passed to it, so we can't use it here
guard let contentTypeUTI = contentTypeUTI as String?,
let url = url as URL?,
let mutableAttributes = mutableAttributes as NSMutableDictionary?
else {
return false
}
var attributes: [AnyHashable: Any] = mutableAttributes as NSDictionary as Dictionary
// Call custom global function to import attributes
let result = importAttributes(&attributes, forFileAt: url, contentTypeUTI: contentTypeUTI)
mutableAttributes.removeAllObjects()
mutableAttributes.addEntries(from: attributes)
return DarwinBoolean(result)
}
))
wrapperPtr.initialize(to: (vtablePtr: vtablePtr, instance: unmanaged.toOpaque()))
return instance
}
}
Finally, I created an #objc class that exposes this allocate function to Obj-C, where I can call it from main.m, and return the pointer to the wrapper block from the factory function. This was necessary because I didn't want to use the unstable #_cdecl attribute to expose a Swift function directly to the plug-in loader.
#objc public final class PluginFactory: NSObject {
#objc public static func createPlugin(ofType type: CFUUID, factoryUUID: CFUUID) -> UnsafeMutableRawPointer? {
if UUID(type) == kMDImporterTypeID {
return UnsafeMutableRawPointer(ImporterPlugin.allocate(factoryUUID: factoryUUID).wrapperPtr)
}
return nil
}
}
// main.m
void *MyImporterPluginFactory(CFAllocatorRef allocator, CFUUIDRef typeID) {
return [PluginFactory createPluginOfType:typeID factoryUUID:CFUUIDCreateFromString(NULL, CFSTR("your plugin factory uuid"))];
}
See my blog post for more details.
Since Apple introduced Swift as a language to be perfectly compatible with any existing Objective-C project I would suggest you just start with whatever makes things easier for you.
If you know Swift best then nothing keeps you from using that – for whatever project you might want. If you want to follow a tutorial that was written for Objective-C and not updated for Swift yet, I think you have two choices (I'd personally recommend going for the second option for now):
Write the same logic written in Objective-C within the tutorial now in Swift from scratch (nearly everything possible in Objective-C is easily possible with Swift, too). For that you need to understand the basics of Objective-C and the corresponding syntax and features in Swift though.
Start with Objective-C to follow the tutorial and keep things easier at the beginning (no need to really understand the tutorials details). Then use the great possibility of mix and matching Swift code alongside Objective-C code to customize the code for your needs or to extend it with your own pre-existing classes.
More specifically on the second option:
If you want to write new classes just use Swift – you can perfectly use everything written in Objective-C from within Swift and vice versa. If you feel you need to change classes already written in Objective-C you have these options: Extend the class written in Objective-C with a new Swift class, re-write that specific file in Swift or just edit the Objective-C file directly.
To learn more on how to mix and match Swift code alongside Objective-C I recommend reading Apples official documentation. It's part of the free iBook "Using Swift with Cocoa and Objective-C" written by Apple engineers for developers.
Unfortunately Apple actually does seem to provide their template for a Spotlight Importer from within XCode for Objective-C only at the moment. Don't know why this is though – I can't see anything stopping them from supporting Swift. We should probably report this with Apples Bug Reporter to stress the fact that people are actually asking for this.
Hope I didn't overlook anything here, otherwise my answer will be pointless. ^^
UPDATE (request)
Here are some steps on where to begin to implement the first approach:
First create a Spotlight Importer project with the latest XCode version
– Create a new "Cocoa Touch" class named exactly the same as your pre-created main Objective-C classes (e.g. "MySpotlightImporter")
Choose Swift and "Create Bridging Header" when asked during class creation
– Re-implement the code written in the ObjC-MySpotlightImporter class within the Swift class (you might want to create a Cocoa App with Core Data support in Swift and Objective-C to get some idea of their differences)
– I'm not sure if you can rewrite the GetMetaDataFile.m in Swift, too, I couldn't figure that out in my test, so you maybe need to keep it around (for now)
– In case you receive any errors along the way that point to some missing configuration just search for the related files/classes in the projects "Build settings" and apply your changes there
I hope this helps to get you started and is specific enough. I tried to do the necessary changes myself in order to provide an example project in Swift but unfortunately I couldn't get it working in a limited time. You may want to consider providing your code publicly though (e.g. on GitHub with a link posted here) in case you decide to port it yourself so others can profit from this, too.
Good luck!

Autopopulateregionbehaviour + MEF

I am writing a new application which registers views within regions automatically using the PRISM AutoPopulateRegionBehaviour. This works fine when I register the views at app startup, however I am trying to use the MEF DeploymentCatalog to download a new XAP and update the region however this doesn't appear to be working (no views are displayed) and setting a breakpoint in the region behaviour. I'll try and upload a small snippet later but I wanted to pre-empt whether this should be possible or whether I need to call something to force the regions to refresh.
Thanks.
Sorted. The problem was that the RegisteredViews Import wasn't being satisfied, the reason for this was that I was importing the viewmodel by interface type rather than by concrete type i.e.
I renamed:
[Import]
public IABCViewModel ViewModel
{
set
{
this.DataContext = value;
}
}
to:
public ABCViewModel ViewModel
{
set
{
this.DataContext = value;
}
}
I think this is because I need to register a type mapping for the interface to the concrete type (though this wasnt necessary in WPF).

Visual Studio 2010 Extension - events not called

I trying to hook several Visual Studio events. Unfortunately I am failing in the first step. The event handlers are never called.
So my question is what I am doing wrong?
Here a little excerpt of my code.
// here are some attributes
[ProvideAutoLoad(VSConstants.UICONTEXT.SolutionExists_string)]
public sealed class VSPackage : Package {
EnvDTE80.DTE2 dte_;
EnvDTE.DocumentEvents documentEvents_;
EnvDTE.WindowEvents windowEvents_;
public VSPackage2Package() {
Trace.WriteLine("I am get called.");
}
protected override void Initialize() {
Trace.WriteLine("I am get called too.");
dte_ = (EnvDTE80.DTE2) System.Runtime.InteropServices.Marshal.
GetActiveObject("VisualStudio.DTE.10.0");
windowEvents_ = dte_.Events.WindowEvents;
documentEvents_ = dte_.Events.DocumentEvents;
windowEvents_.WindowCreated +=
new EnvDTE._dispWindowEvents_WindowCreatedEventHandler(
windowEvents_WindowCreated);
documentEvents_.DocumentOpened +=
new EnvDTE._dispDocumentEvents_DocumentOpenedEventHandler(
documentEvents__DocumentOpened);
Trace.WriteLine("Everything fine until here.");
}
void documentEvents__DocumentOpened(EnvDTE.Document document) {
Trace.WriteLine("Never called");
}
void windowEvents_WindowCreated(EnvDTE.Window window) {
Trace.WriteLine("Never called");
}
}
Edit:
I get it working, looking at other sample code, I figured out that they sometimes getting the DTE object differently. Changing
dte_ = (EnvDTE80.DTE2) System.Runtime.InteropServices.Marshal.
GetActiveObject("VisualStudio.DTE.10.0");
to
dte_ = GetService(typeof(EnvDTE.DTE)) as EnvDTE80.DTE2;
and now everything is fine.
It should work.
I'm pretty sure that if you do the same from an Addin it would work. Packages can be painfull sometimes.
In fact, when a package is loaded the shell (DTE) may not be fully loaded yet. Try to register your events when it is.
To do so, use the OnShellPropertyChange event and the Zombie state to know when to register.
http://social.msdn.microsoft.com/forums/en-US/vsx/thread/3097a0e1-68e3-47ea-a4ba-8511571b2487/
Read the following, I think it answers your question. Note : The GetService method is the same as calling GetGlobalService.
1. ServiceProvider.GlobalProvider
This new static property on the
ServiceProvider class allows access to
the global service provider from any
code, as long as it is called from the
main UI thread. This property is
closely related to the
Package.GetGlobalService static method
which was available in previous
versions of the MPF. The problem with
Package.GetGlobalService was that it
would fail if a package had not yet
been initialized. This led to subtle
ordering bugs in code that used the
MPF libraries without initializing a
package of their own. Sometimes they
would work only because another
package had already initialized the
global ServiceProvider on their
behalf. If that other package was
uninstalled, or perhaps moved to a
different version of the MPF, that
static would no longer be initialized
causing Package.GetGlobalService to
fail.
Now, in MPF 10, you can call
ServiceProvider.GlobalProvider at any
time as long as you are calling from
the UI thread. For compatibility, this
mechanism will still use the
ServiceProvider created by the first
Package to be sited but, in the case
where no Package has yet been
initialized, MPF 10.0 now has the
ability to obtain the global provider
from the registered COM message
filter. Package.GetGlobalService() is
also hooked up to this new mechanism.
Make sure you are not boxing and unboxing your DTE object. I found this was the issue for me.
See my solution here: http://social.msdn.microsoft.com/Forums/en-US/vsx/thread/eb1e8fd1-32ad-498c-98e9-25ee3da71004

Resources