Is there a cleaner way of writing the conditional for case "1", "4", "7"? For this case I want to write to the string "b" only if the string value is not "4".
var b = ""
var c = ""
let s = "4"
switch s {
case "0", "6", "8":
c += "|_|"
case "1", "4", "7":
if s != "4" { b += " |" }
c += " |"
case "2":
c += "|_ "
case "3", "5", "9":
c += " _|"
default:
c += ""
}
This is a place you could use the fallthrough statement:
switch s {
case "0", "6", "8":
c += "|_|"
case "1", "7":
b += " |"
fallthrough
case "4":
c += " |"
case "2":
c += "|_ "
case "3", "5", "9":
c += " _|"
default:
break
}
Since you want "1" and "7" to execute both statements, give them their own case and then follow it with fallthough which allows it to fall though to the next case. Then "1", "4", and "7" will all execute the code in the case "4": case.
I think the whole idea of switch statement is that you don’t use ifs inside. You should probably just create a separate case for “4”. The amount of space saved by putting this conditional isn’t worth obscuring the code IMO.
Related
In my app I have a data pull from Firebase. I have a UITableViewController and would like to insert in a row a text from within the app. The data pull would be like this (please excuse the bad example but I cannot go into too much detail ..)
The original data pull:
Row 1: abc
Row 2: def
Row 3: ghi
Row 4: jkl
Row 5: mno
What I would like to achieve:
Row 1: abc
Row 2: def
Row 3: text from the app
Row 4: ghi
Row 5: jkl
Row 6: text from the app
Row 7: mno
How can I achieve this? I was trying to do something like this in cellForRowAt
if indexPath.row % 3 == 0 {
cell.text = "custom text"
}
But this is replacing every 3rd rows content. I would like to put a row in between, so to speak.
You can modify your server data with local data.
var serverData = ["a","b","c","d","e","f","g","h","i","j","k","l","m"]
let localAppData = ["1","2","3","4","5","6","7","8","9","10"]
var modified = [String]()
var counter = 0
for index in 1...serverData.count {
let value = serverData[index - 1]
if index % 3 == 0 && index != 0 {
if counter < localAppData.count {
modified.append(localAppData[counter])
}else{
modified.append(value)
}
counter += 1
}else{
modified.append(value)
}
}
serverData.removeAll()
serverData.append(contentsOf: modified)
print(serverData) //["a", "b", "1", "d", "e", "2", "g", "h", "3", "j", "k", "4", "m"]
if counter < localAppData.count {
// Appeds the remain local data to your serverData
serverData.append(contentsOf: localAppData[counter...localAppData.count-1])
}
print(serverData) //["a", "b", "1", "d", "e", "2", "g", "h", "3", "j", "k", "4", "m", "5", "6", "7", "8", "9", "10"]
Note: After modification you have to reload the tableView
You can update the datasource by inserting the value at 3rd position and use that datasource in cellforrowat
var a = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]
var temp = a
for (ind, _) in a.enumerated() {
if ind % 3 == 0 && ind != 0 {
temp.insert("current text", at: ind)
}
}
print(temp) // Prints ["a", "b", "c", "current text", "d", "e", "current text", "f", "g", "h", "i"]
Hello I am getting error "Missing '=' operator after key in hash literal." on the IF statement, where am I wrong
$Nests | ForEach-Object {
$RecordMetrics = [pscustomobject]#{
key = $_.key
count = $_.doc_count
if (key -like 'CBT99*')
{
bo = 'CBT'
SiteID = 1972
}
elseif
{
boperator = $map[$_.key.TrimEnd("1","2","3","4","5","6","7","8","9","0","-") ].boperator
SiteID = $map[$_.key.TrimEnd("1","2","3","4","5","6","7","8","9","0","-") ].SiteID
}
}}
You can't put a conditional statement in the middle of a hashtable literal like that.
You'll have to create the hashtable/dictionary first, then populate the relevant keys based on your conditional logic:
$Nests | ForEach-Object {
# create dictionary with initial properties
$properties = [ordered]#{
key = $_.key
count = $_.doc_count
Host = ''
OperatorName = ''
}
# conditionally add remaining properties
if ($_.key -like 'CBT99*') {
$properties['bo'] = 'CBT'
$properties['SiteID'] = 1972
}
else {
$properties['boperator'] = $map[$_.key.TrimEnd("1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "-") ].boperator
$properties['SiteID'] = $map[$_.key.TrimEnd("1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "-") ].SiteID
}
# convert to custom object
$RecordMetrics = [pscustomobject]$properties
}
I am working on an API module in scala which queries DB and returns the fetched data in JSON format as the response.
For a particular attribute in the JSON(whose type is Option[String]) , I need to alter the value fetched from DB based on certain conditions.
Currently , my JSON response looks like this:
.....
{
"id": "1",
"name": "abc",
"osType": "windows",
"osVersion": "10.0.14393"
},
{
"id": "2",
"name": "xyz",
"osType": "ubuntu",
"osVersion": "18.04"
},
{
"id": "3",
"name": "pqr",
"osType": "windows",
"osVersion": "6.1.7601"
},
......
I need to substitute the following values for osVersion for records with "osType": "windows"
if osVersion = 10.0.14393 , then Windows Server 2016
if osVersion starts with 6.1 , then Windows Server 2008 R2
So that desired output looks like this:
.....
{
"id": "1",
"name": "abc",
"osType": "windows",
"osVersion": "Windows Server 2016"
},
{
"id": "2",
"name": "xyz",
"osType": "ubuntu",
"osVersion": "18.04"
},
{
"id": "3",
"name": "pqr",
"osType": "windows",
"osVersion": "Windows Server 2008 R2"
},
......
I tried using if-else and pattern-matching , but am unable to substitute correctly as the type is Option[String].
This is how I tried:
(1)
def translateOSVersion (osType :Option[String] ,osVersion : Option[String]):Option[String] ={
if (osType == "windows"){
val version = if (osVersion =="10.0.14393")
{
Some("Windows Server 2016")
}
else {osVersion}
version
}
}
val oSVersion = translateOSVersion(ostr("osType") ,ostr("osVersion") )
<modelJSON>(id, name, ostr("osType"), oSVersion)
(2)
def translateOSVersion (osType :Option[String] ,osVersion : Option[String]) ={
if (osType == "windows"){
val version = if (osVersion =="10.0.14393") Some("Windows Server 2016")
else osVersion
}
}
val oSVersion = Some(translateOSVersion(ostr("osType") ,ostr("osVersion") ).toString)
<modelJSON>(id, name, ostr("osType"), oSVersion)
(3)
def translateOSVersion (osType :Option[String] ,osVersion : Option[String]) ={
if (osType == "windows"){
osVersion match {
case Some("10.0.14393") => "Windows Server 2016"
case x =>x
}
}
}
val oSVersion = Some(translateOSVersion(ostr("osType") ,ostr("osVersion") ).toString)
<modelJSON>(id, name, ostr("osType"), oSVersion)
All the approaches do not result in desired result.
Kindly help here.
Something like this should work:
def translateOSVersion(osType: Option[String], osVersion: Option[String]): Option[String] =
(for {
ot <- osType if ot == "windows"
ov <- osVersion
} yield {
if (ov == "10.0.14393") {
"Windows Server 2016"
} else if (ov.startsWith("6.1")) {
"Windows Server 2008 R2"
} else {
ov
}
}) orElse osVersion
This is how it works:
The for statement creates a new Option[String] representing the updated version number, or None if there is no change. It works by extracting the two Option values into ot for the OS Type and ov for the OS Version. If either of the Options is None it will return None, and it will also return None if the OS type is not "windows". If all these tests pass, the yield expression computes the new version based on these values. In this case the for will return Some(x) where x is the value of the yield expression.
The orElse expression will return the first value if it is Some(x), otherwise it will return the second value. So if the result of the for is Some(x) then it is returned as the result of the function. If the for returns None then the original value is returned as the result.
This is a more prosaic version that is probably more suitable, though less fun!
def translateOSVersion(osType: Option[String], osVersion: Option[String]): Option[String] =
if (osType.contains("windows")) {
if (osVersion.contains("10.0.14393")) {
Some("Windows Server 2016")
} else if (osVersion.exists(_.startsWith("6.1"))) {
Some("Windows Server 2008 R2")
} else {
osVersion
}
} else {
osVersion
}
Thanks for your help - just starting out so imagine there's some serious issues with my logic here.
Trying to write a program, given an input, if a letter from that input is found in a dictionary, replace the letter with the corresponding value.
Really stuck where I'm going wrong. Anyone able to help / suggest an alternative logic that may work?
var leetDic = ["A" : "4",
"B" : "6",
"E" : "3",
"I" : "1",
"L" : "1",
"M" : "(V)",
"N" : "(/)",
"O" : "0",
"S" : "5",
"T" : "7",
"V" : "(/",
"W" : "`//]"]
func leetConverter(leet: String) {
var leet1 = leet.uppercased()
for i in leet1.characters {
if i == leetDic.keys { //ERROR "Binary operator cannot be applied to operands of type Character and dictionary"
i = leetDic.values // ERROR "cannot assign value 'i' is a let constant"
} else {
return i
}
}
}
var test = leetConverter(leet: "Hello World")
Problem is you are comparing character and array also you can assign value to i in loop because it is constant you can go like this way.
func leetConverter(leet: String) -> String {
var leet1 = leet.uppercased()
var newString = String()
for ch in leet1.characters {
let str = String(ch)
if let value = leetDic[str] {
newString.append(value)
} else {
newString.append(str)
}
}
return newString
}
More Swifty way
func leetConverter(leet: String) -> String {
let str = leet.characters.map { leetDic[String($0).uppercased()] ?? String($0) }.joined()
return str
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I have a string let string = "!101eggs". Now, I want to have an array like this ["!", "101", "e", "g", "g", "s"]. How can I do this?
I presume the hard part for you is "Where's the number"? As long as this is just a simple sequence of digits, a regular expression makes it easy to find:
let string = "!101eggs"
let patt = "\\d+"
let reg = try! NSRegularExpression(pattern:patt)
let r = reg.rangeOfFirstMatch(in: string,
options: [],
range: NSMakeRange(0,string.utf16.count)) // {1,3}
So now you know that the number starts at position 1 and is 3 characters long. The rest is left as an exercise for the reader.
Sorry It's too long
when input is
print("-1-2a000+4-1/000!00005gf101eg14g1s46nj3j4b1j5j23jj212j4b2j41234j01010101g0000z00005g0000".toArrayByNumber())
Result: ["-", "1", "-", "2", "a", "000", "+", "4", "-", "1", "/", "000", "!", "00005", "g", "f", "101", "e", "g", "14", "g", "1", "s", "46", "n", "j", "3", "j", "4", "b", "1", "j", "5", "j", "23", "j", "j", "212", "j", "4", "b", "2", "j", "41234", "j", "01010101", "g", "0000", "z", "00005", "g", "0000"]
extension Int {
func toZeroString() -> String {
return (0 ..< self).reduce("", { (result, zero) -> String in
return result + "0"
})
}
}
extension String {
func toArrayByNumber() -> [String] {
var array: [String] = []
var num = 0
var zeroCount = 0
var zeroEnd = false
for char in self.characters {
if let number = Int("\(char)") {
if zeroEnd == false && number == 0 {
zeroCount += 1
} else {
num = num * 10 + number
zeroEnd = true
}
} else {
if num != 0 {
array.append(zeroCount.toZeroString() + ("\(num)"))
} else if zeroCount > 0 {
array.append(zeroCount.toZeroString())
}
array.append(String(char))
num = 0
zeroCount = 0
zeroEnd = false
}
}
if num != 0 {
array.append(zeroCount.toZeroString() + ("\(num)"))
} else if zeroCount > 0 {
array.append(zeroCount.toZeroString())
}
return array
}
}