How to compare Obj C enum in Swift? - ios

I am using FreeStreamer in Swift and am trying to set the onStateChange block.
audioStream.onStateChange = { (state) in
if state == kFsAudioStreamBuffering {
//blah
}
}
I am getting this error:
Binary operator '==' cannot be applied to operands of type '(FSAudioStreamState)' and 'FSAudioStreamState'
Edit: Still the same error without the parentheses around state in the block params
EDIT: As a temporary fix, state.value == kFsAudioStreamBuffering.value works

try putting a dot (.) before kFsAudioStreamBuffering
something like this:
if state == .kFsAudioStreamBuffering {
//blah
}
UPDATE: Try this instead
audioStream.onStateChange = { state in
if state.value == kFsAudioStreamBuffering.value {
//blah
}
}

It should be something like this to make it work.
self.audioControler?.onStateChange = { (state:FSAudioStreamState) -> Void in
switch state {
case .fsAudioStreamRetrievingURL:

Related

Dart streams error with .listen().onError().onDone()

I have an issue with some code that looks like this. In this form I have an error
The expression here has a type of 'void', and therefore can't be used.
Try checking to see if you're using the correct API; there might be a function or call that returns void you didn't expect. Also check type parameters and variables which might also be void.dart(use_of_void_result).
If I remove the .onDone() the error goes away. Why? ELI5 please :-)
I was looking at https://api.dart.dev/stable/2.7.0/dart-async/Stream/listen.html but seem to still be misundertanding something.
I also read https://api.dart.dev/stable/2.7.0/dart-async/StreamSubscription/onDone.html
serviceName.UploadThing(uploadRequest).listen((response) {
uploadMessageOutput = response.message;
if (response.uploadResult) {
showSuccess();
} else {
showError();
}
getUploadFileList(event);
isSaveInProgress = false;
}).onError((error) {
isSaveInProgress = false;
_handleFileUploadError(uploadRequest, error);
}).onDone(() {
isSaveInProgress = false;
});
Your code is almost right, but will only require a simple change to work correctly.
You would be seeing the same error if you swapped the ordering of onError and onDone, so the issue has nothing to do with your stream usage. However, you're attempting to chain together calls to onError and then onDone which won't work since both of these methods return void.
What you're looking for is cascade notation (..), which will allow for you to chain calls to the StreamSubscription returned by listen(). This is what your code should look like:
serviceName.UploadThing(uploadRequest).listen((response) {
uploadMessageOutput = response.message;
if (response.uploadResult) {
showSuccess();
} else {
showError();
}
getUploadFileList(event);
isSaveInProgress = false;
})..onError((error) { // Cascade
isSaveInProgress = false;
_handleFileUploadError(uploadRequest, error);
})..onDone(() { // Cascade
isSaveInProgress = false;
});

complementery of an if case

How would you write this:
if case .SomeEnum(3) = enumType where myInt == 3 {
//I don't need this case
} else {
//This is the case I need
}
I know I could use guard:
guard case .SomeEnum(3) = enumType where myInt == 3 else {
//This is the case I need
}
but I don't think it is clean, since it is not really a case in which the function is not able to finish. Also, guard expects me to return from the function.
Any other alternatives?
You cannot negate a pattern (as far as I know), and your first solution
using if/else looks fine to me, the intention of the code is clearly
visible.
A switch statement would be an alternative:
switch enumType {
case .SomeEnum(3) where myInt == 3:
break // I don't need this case
default:
// This is the case I need
// ...
}
With regard to your remark
Also, guard expects me to return from the function.
that is not entirely true. You are expected to leave the current scope.
So this would compile and work as expected:
repeat {
guard case .SomeEnum(3) = enumType where myInt == 3 else {
// This is the case I need
// ...
break
}
} while false
but I would not consider that a better solution.

Why does authenticate directive lead to "Error: type mismatch"?

I'm getting this error in my spray project.
Error:(41, 28) type mismatch;
found : spray.routing.authentication.ContextAuthenticator[co.s4n.authentication.entities.Usuario]
(which expands to) spray.routing.RequestContext => scala.concurrent.Future[scala.util.Either[spray.routing.Rejection,co.s4n.authentication.entities.Usuario]]
required: spray.routing.directives.AuthMagnet[?]
authenticate(validateToken) {
^
This is my TokenValidator trait
trait TokenValidator {
def validateToken: ContextAuthenticator[Usuario] = {
ctx =>
val header = ctx.request.headers.find(_.name == "Access_Token")
if (header isDefined) {
doAuth(header.get)
}
else {
Future(Left(AuthenticationFailedRejection(AuthenticationFailedRejection.CredentialsMissing, List())))
}
}
def doAuth(header: HttpHeader): Future[Authentication[Usuario]] = {
Dao.validateToken(header.value).map {
case Some(usuario) => Right(usuario)
case None => Left(AuthenticationFailedRejection(AuthenticationFailedRejection.CredentialsRejected, List()))
}
}
}
and this is the line where I¡m getting that error
//#DELETE
//localhost:9090/authenticacion/users/{{userEmail}}
val `users/{{email}}` =
pathPrefix(`path-prefix`) {
pathPrefix(`users-path-prefix` / Segment) {
emailRef => {
delete {
authenticate(validateToken) { **HERE!!!!**
usuario =>
.....
}
}
}
}
}
Does anyone know what am I doing wrong?
Thak you all in advance!
The only thing I was missing was to have ExecutionContext in scope and import ExecutionContext.Implicits.global worked fine.
It's to let Futures work as they declare an implicit ExecutionContext parameter.
I know it's a long time since the actual question came, but the way to go with this for Spray is to determine the execution context with the tools that Spray provides:
implicit def executionContext = actorRefFactory.dispatcher

Issue with DevExpress XtraTabControl

I am having a DevExpress XtraTabControl with 3 XtraTabPages.
I am trying to remove a Tabpage based on a condition and after removing for the last iteration,it is getting error.
My Code is
foreach (DevExpress.XtraTab.XtraTabPage ptp in tabContactsDetails.TabPages)
{
if (tabContactsDetails.TabPages.Contains(ptp))
{
if (ptp.Name == "tabPTP")
{
if (maxid == String.Empty || maxid == null || maxid == "lblHiddenDebtorID")
{
tabContactsDetails.TabPages.Remove(ptp);
}
else
{
}
}
}
}
and I am getting an error like
Collection was modified; enumeration operation may not execute.
You cannot change a collection while iterating through it!
What I do is the following:
List<XtraTabPage> tabPagesToBeRemoved = new List<XtraTabPage>();
foreach (XtraTabPage ptp in tabContactsDetails.TabPages)
{
if (shouldBeRemoved())
{
tabPagesToBeRemoved.Add(ptp);
}
}
foreach (XtraTabPage pageToBeRemoved in tabPagesToBeRemoved)
{
tabContactsDetails.TabPages.Remove(pageToBeRemoved);
}

Human readable key names for characters

I want to trigger some code if the 'A' key is pressed:
document.on.keyDown.add((event) {
if (event.keyIdentifier == 'U+0041') {
...
}
});
Using the unicode code (U+0041) of the character is not very readable. Is there any method I can use to convert the code to a character or vice versa? I would like to do something like this:
document.on.keyDown.add((event) {
if (event.keyIdentifier == unicodeCode('A')) {
...
}
});
I hope this will help:
document.on.keyPress.add((KeyboardEvent event) {
final String char = new String.fromCharCodes([event.charCode]);
print('Key: $char');
if (event.keyIdentifier == 'U+0041') {
print('$char pressed.');
}
if (char == 'a') {
print('Lowercase "a" has been pressed.');
}
});
Currently the keyDown event doesn't provide the appropriate charCodes.

Resources