How does let x where x.hasSuffix(pepper) work
vegetable
is an implicit String
. It's the same as you would write:
var vegetable: String = "red pepper"
hasSuffix
is declared as func hasSuffix(suffix: String) -> Bool
an therefore returns a Bool
. The where
keyword specifies additional requirements, and can only be used in switch
statements.
Because all of this is suffused, the vegetable
variable is assigned to x (let x
).
You can read more about the where
and switch
here.
What is meaning of where keyword?
The where
in that context is used as pattern matching. From the example:
case let x where x.hasSuffix("pepper"):
When the suffix of x
matches "pepper"
it will set the constant vegetableComment
:
let vegetableComment = "Is it a spicy \(x)?"
You can see as well that x
can´t be "celery", "cucumber" or "watercress", otherwise it would give you a different outcome:
case "celery":
let vegetableComment = "Add some raisins and make ants on a log."
case "cucumber", "watercress":
let vegetableComment = "That would make a good tea sandwich."
Because those cases are before case let x where x.hasSuffix("pepper"):
. You can try changing the order of them and pass the value "celery" to see a different outcome.
Edit:
From my understanding it creates a constant x
if x
's suffix is "pepper". The goal of creating this constant, is for you to use it after that:
let vegetableComment = "Is it a spicy \(x)?"
Edit 2:
After a bit more research, that's called value binding and it's described as:
switch case can bind the value or values it matches to temporary
constants or variables, for use in the body of the case. This is known
as value binding, because the values are “bound” to temporary
constants or variables within the case’s body.
Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks. https://itun.es/gb/jEUH0.l
Swift Constant Assignment Example
The where
predicate could directly reference vegetable
, this this particular situation, and it compiles fine.
switch vegetable {
case "celery":
print("Add some raisins and make ants on a log.")
case "cucumber", "watercress":
print("That would make a good tea sandwich.")
case let x where vegetable.hasSuffix("pepper"):
print("Is it a spicy \(x)?")
default:
print("Everything tastes good in soup.")
}
But now consider a more complex patternmatching of vegetable
, supposing that it were a String?
(a.k.a. Optional<String>
) and not String
:
let vegetable: String? = "red pepper"
switch vegetable {
case "celery"?:
print("Add some raisins and make ants on a log.")
case "cucumber"?, "watercress"?:
print("That would make a good tea sandwich.")
case let x? where vegetable.hasSuffix("pepper"):
// ^ error: value of optional type 'String?' not unwrapped; did you mean to use '!' or '?'?
print("Is it a spicy \(x)?")
case nil:
print("You don't even have a vegetable!")
default:
print("Everything tastes good in soup.")
}
In this case, x
is the non-optional value of vegetable
in a non-nil case, which allows use to call .hasSuffix("pepper")
on it. It's saying "If it is the case that vegetable has a value, call it x
, that happens to end with "pepper"
, then do this: ..."
Error: value of type 'String' has no member 'hasSuffix' in Swift switch
The hasSuffix(_:)
member of String
is bridged from NSString
(and in so from Foundation). When working with Swift in Xcode Playgrounds and projects, this method is available from the Swift standard library, whereas when compiling Swift from e.g. the IBM sandbox/your local Linux machine, the Swift std-lib version is not accessible, whereas the one from core-libs Foundation is.
To have access to the latter implementation, you need to explicitly import Foundation:
import Foundation // <---
let vegetable = "red pepper"
switch vegetable {
case "celery":
print("Add some raisins and make ants on a log.")
case "cucumber", "watercress":
print("That would make a good tea sandwich.")
case let x where x.hasSuffix("pepper"):
print("Is it a spicy \(x)?")
default:
print("Everything tastes good in soup.")
}
Most Swift tutorials will assume execution via Xcode, and import Foundation
can be good first attempted remedy for any "... has no member ..." errors when compiling Swift outside of Xcode.
Details
As @Hamish points out in a comment below (thanks!), one implementation of hasSuffix(_:)
is available from the standard library, with the requirement of _runtime(_ObjC)
, however.
From swift/stdlib/public/core/StringLegacy.swift:
#if _runtime(_ObjC)
// ...
public func hasSuffix(_ suffix: String) -> Bool {
// ...
}
#else
// FIXME: Implement hasPrefix and hasSuffix without objc
// rdar://problem/18878343
#endif
Another implementation can be used in case the one above is not accessible (e.g. from Linux). Accessing this method requires an implicit import Foundation
statement, however.
From swift-corelibs-foundation/Foundation/NSString.swift:
#if !(os(OSX) || os(iOS))
extension String {
// ...
public func hasSuffix(_ suffix: String) -> Bool {
// ... core foundation implementation
}
}
#endif
Swift where key word
Swift's switch
statements are much more powerful than the ones used in most other languages. Instead of simply choosing from a group of values, they use pattern-matching to select which case
to evaluate. Let's look at each case
from your example:
case "celery":
Super simple -- this will match the string "celery"
and nothing else.
case "cucumber", "watercress":
This case will match either the string "cucumber"
or the string "watercress"
. Cool. In other languages you'd probably need to use a fallthrough case to get both of these.
case let x where x.hasSuffix("pepper"):
This case contains two concepts that are particular to Swift switch
statements, when compared to Java and C. The first is value-binding -- the let x
part of this statement binds the matched value to a constant x
that is scoped to the case's body.
Next is the where
clause. This is a boolean test, just like an if
statement, so the case only matches if the expression is true
. In this example, x.hasSuffix("pepper")
looks at the bound value and checks to see if it ends with "pepper"
. The strings "red pepper"
, "green pepper"
, and "spicy hot pepper"
would all match, but "peppercorns"
would not.
default:
In Swift, switch
statements need to exhaust all the possible values of the matched value, so they typically end with a default:
case block to handle any value that wasn't previously matched. The only time you wouldn't see this is if you're matching an enum
with only a few values, since you could manually exhaust all the options.
Noop for Swift's Exhaustive Switch Statements
According to the book, you need to use break
there:
The scope of each case can’t be empty. As a result, you must include at least one statement following the colon (:) of each case label. Use a single
break
statement if you don’t intend to execute any code in the body of a matched case.
Detecting Pepper (PPAPI) Flash with Javascript
I think it should be done this way:
var isPPAPI = false;
var type = 'application/x-shockwave-flash';
var mimeTypes = navigator.mimeTypes;
if (mimeTypes && mimeTypes[type] && mimeTypes[type].enabledPlugin &&
mimeTypes[type].enabledPlugin.filename == 'pepflashplayer.dll') isPPAPI = true;
Demo on jsFiddle.
UPD №1: Not sure if needed, but I wrote a little explanation:
If our browser has a MIME types enumeration, we can get a plugin associated with a specified type. So we're getting plugin which associated with 'application/x-shockwave-flash'
and check if its filename is 'pepflashplayer.dll'
. I think that this name is constant and will not be changed in future.
UPD №2:
To enable/disable PPAPI in Google Chrome, you should go to this page: chrome://plugins/
(Sorry, this URL needs to be pasted directly into the address bar.)
UPD №3:
I did some investigation and found an interesting article that helped me to implement a cross-platform solution. I think that this code should work on all OS:
var isPPAPI = false;
var type = 'application/x-shockwave-flash';
var mimeTypes = navigator.mimeTypes;
var endsWith = function(str, suffix) {
return str.indexOf(suffix, str.length - suffix.length) !== -1;
}
if (mimeTypes && mimeTypes[type] && mimeTypes[type].enabledPlugin &&
(mimeTypes[type].enabledPlugin.filename == "pepflashplayer.dll" ||
mimeTypes[type].enabledPlugin.filename == "libpepflashplayer.so" ||
endsWith(mimeTypes[type].enabledPlugin.filename, "Chrome.plugin"))) isPPAPI = true;
Check out an updated fiddle.
UPD №4:
Slightly changed the code to meet today's realities. Now condition looks like this:
if (mimeTypes && mimeTypes[type] && mimeTypes[type].enabledPlugin &&
(mimeTypes[type].enabledPlugin.filename.match(/pepflashplayer|Pepper/gi))) isPPAPI = true;
Check out jsFiddle.
Implementing the intelligent recursive algorithm in matlab
From the paper it seems that the "impulse pixels" are just the noisy pixels, in the case of salt & pepper noise. Furthermore, it also seems that the algorithm provides an "intelligent" mechanism to calculate the denoised value of a noisy pixel if its value is above a threshold (which it calculates adaptively).
So, what about "If X(i,j) ≠ Impulse pixel " ? Well, apparently, the authors assume to know (!) which pixels are noisy (!!), which makes the whole thing rather ridiculous, since this info is almost impossible to know.
I might also add that the rather stunning results presented in the paper are most probably due to this fact.
P.S. Regarding the argument that <"impulse pixels" are all the pixels a which are either equal to 0 or 255>, it is wrong. The set of pixels that have either 0 or 255 intensity value, includes the noisy pixels as well as proper pixels that just happen to have such a value. In this case, the algorithm will most probably collapse since it will denoise healthy pixels as well.
Related Topics
Xcode UI Test:Accessibility Query Fail on Uitableviewcell
Swift Protocol Defining Class Method Returning Self
Swift/Scenekit Problems Getting Touch Events from Scnscene and Overlayskscene
Swift Codable - Parse JSON Array Which Can Contain Different Data Type
How to Send Data from iPhone to Watchkit in Os2 in Swift
Different Portrait/Landscape Views in Storyboard and Swift
Getting a Segmentation Fault: 11 with Swift 5.2 When Using Filemanager.Default.Currentdirectorypath
Swift - How to Get Text Formatting in a Text Editor Like in the Notes App? Swiftui
From Any Utf-16 Offset, Find the Corresponding String.Index That Lies on a Character Boundary
Combining Custom Property Wrapper with @Published
Can Not Conform to Protocol by Creating Extension with Where Clauses
How to Convert Text to Speech for Osx in Swift Playground
Compactmap on Sequence() Not Lazy
Swift; Delegate Embedded View Controller and Parent