Here is the code:
let answer = randomIntBetween(1, high: 100)
print("Enter a number between 1 and 100!")
let userInput = input()
let inputAsInt = userInput.toInt()
if let guess = inputAsInt {
if (guess > answer) {
print("Your guess was too high!")
} else if (guess < answer) {
print("Your guess was too low!")
} else {
print("You got it dead on! The answer was \(answer)!")
}
} else {
print("Not a valid answer, try adding a number!")
}
I am following a guide (only been learning for about a month) and I know .toInt() was removed but what would I need to put in its place?
Down cast replaced it.
let inputAsInt = Int(userInput)
Related
I'm struggling to understand why my code isn't working? Any help/correction is appreciated.
struct DogBowlWithFailableInitializers {
var foodLeft: Int
init?(foodLeft: Int) {
if foodLeft < 0 {
return nil
}
self.foodLeft = foodLeft
}
}
if let negativeDogFoodTest = DogBowlWithFailableInitializers(foodLeft: 10) {
print("Success!")
let negativeDogFoodTest = DogBowlWithFailableInitializers(foodLeft: 10)
}
else {
print("Invalid dog food amount inputted")
}
From my understanding, a new instance should be created since it passed both if statements inside the structure and out. But when I try to access any properties within the instance, I'm not able to, why is that?
print(negativeDogFoodTest.foodLeft) //doesn't work
You don't seem to understand the concept of scoping. Consider this simple if let statement:
if let x = y {
// A
someVariable = x // works
}
// B
someVariable = x // does not work
x is only accessible inside the if statement, i.e. at A. Outside the if statement, i.e. at B, x is out of scope.
Why? Because it makes no sense to access x at B because B is executed whether or not y is nil.
So you should access it inside the if statement.
Another problem is that you declared negativeDogFoodTest twice:
// 1st time
if let negativeDogFoodTest = DogBowlWithFailableInitializers(foodLeft: 10) {
print("Success!")
// 2nd time!
let negativeDogFoodTest = DogBowlWithFailableInitializers(foodLeft: 10)
}
One time is enough!
if let negativeDogFoodTest = DogBowlWithFailableInitializers(foodLeft: 10) {
print("Success!")
print(negativeDogFoodTest.foodleft)
}
You can also consider a guard statement:
guard let negativeDogFoodTest = DogBowlWithFailableInitializers(foodLeft: 10)
else { return }
negativeDogFoodTest is a local variable with scope in the then-branch of your if. It does not exist outside of that block.
So you need to do this:
if let negativeDogFoodTest = ... {
print(negativeDogFoodTest.foodLeft)
}
Note that your second assignment to negativeDogFoodTest is redundant.
You can also use guard instead:
guard let negativeDogFoodTest = ... else {
dealWithFailure()
(return|break|continue)
}
print(negativeDogFoodTest.foodLeft)
I am trying to validate UITextField if it has greater than 3 characters it should return true else return false. I tried using the below code but it is not working. What am I doing wrong?
let validUserNameSignal = self.nameTextField.reactive.trigger(for: .valueChanged).observeValues {
value in
}.map { (value) in
String(describing: value).characters.count > 3 ? true:false
}
print("user name valid result is \(validUserNameSignal)")
Here's how the code should look.
let validUserNameSignal =
self.nameTextField
.reactive
.continuousTextValues
.skipNil()
.map { $0.characters.count > 3 }
validUserNameSignal.observeValues { value in
print("user name valid result is \(value)")
}
I would like to find the first EKSource of type EKSourceType.Local with a "single"-line expression in Swift. Here is what I currently have:
let eventSourceForLocal =
eventStore.sources[eventStore.sources.map({ $0.sourceType })
.indexOf(EKSourceType.Local)!]
Is there a better way of doing this (such as without mapping and/or with a generic version of find)?
Alternatively in Swift3 you could use:
let local = eventStore.sources.first(where: {$0.sourceType == .Local})
There's a version of indexOf that takes a predicate closure - use it to find the index of the first local source (if it exists), and then use that index on eventStore.sources:
if let index = eventStore.sources.indexOf({ $0.sourceType == .Local }) {
let eventSourceForLocal = eventStore.sources[index]
}
Alternately, you could add a generic find method via an extension on SequenceType:
extension SequenceType {
func find(#noescape predicate: (Self.Generator.Element) throws -> Bool) rethrows -> Self.Generator.Element? {
for element in self {
if try predicate(element) {
return element
}
}
return nil
}
}
let eventSourceForLocal = eventStore.sources.find({ $0.sourceType == .Local })
(Why isn't this there already?)
I don't understand why you're using map at all. Why not use filter? You will then end up with all the local sources, but in actual fact there will probably be only one, or none, and you can readily find out by asking for the first one (it will be nil if there isn't one):
let local = eventStore.sources.filter{$0.sourceType == .Local}.first
Swift 4 solution that also handles the situation when there are no elements in your array that match your condition:
if let firstMatch = yourArray.first{$0.id == lookupId} {
print("found it: \(firstMatch)")
} else {
print("nothing found :(")
}
Swift 5 If you want to find out from Array of Model then speciyfy $0.keyTofound otherwise use $0
if let index = listArray.firstIndex(where: { $0.id == lookupId }) {
print("Found at \(index)")
} else {
print("Not found")
}
Let's try something more functional:
let arr = [0,1,2,3]
let result = arr.lazy.map { print("💥"); return $0 }.first(where: { $0 == 2 })
print(result) // 3x 💥 then 2
Whats cool about this?
You get access to element or i while you search. And it's functional.
For Swift 3 you'll need to make a few small changes to Nate's answer above. Here's the Swift 3 version:
public extension Sequence {
func find(predicate: (Iterator.Element) throws -> Bool) rethrows -> Iterator.Element? {
for element in self {
if try predicate(element) {
return element
}
}
return nil
}
}
Changes: SequenceType > Sequence, Self.Generator.Element > Iterator.Element
I have a variable. It contains telephone numbers.
I am using like this:
println(person.phoneNumbers!.map( {$0.value} ))
Output:
[555-478-7672, (408) 555-5270, (408) 555-3514]
You can see there are three phone numbers. How can I iterate this variable?
I need something like this:
Phone 1: 555-478-7672
Phone 2: (408) 555-5270
Phone 3: (408) 555-3514
This solution is for Swift 1.2
for (index, number) in enumerate(person.phoneNumbers!.map { $0.value }) {
println("Phone \(index): \(number)")
}
And since I am scared by this ! I would go with the following version
if let numbers = person.phoneNumbers {
for (index, number) in enumerate(numbers.map { $0.value }) {
println("Phone \(index): \(number)")
}
}
Update
The following code tries to answer the question added in the comments below.
if let numbers = person.phoneNumbers {
let list = numbers.map { $0.value }
let json : [String:AnyObject] = ["phoneNumbers": list]
}
Update #2
Please find below the second block of code, updated for Swift 2.0
if let numbers = person.phoneNumbers {
for (index, number) in (numbers.map { $0.value }).enumerate() {
print("Phone \(index): \(number)")
}
}
You can do it like this.
for number in person.phoneNumbers!.map( {$0.value} ) {
println(number)
}
Do it like this,
let extracted = person.phoneNumbers.enumerate().map { index, phone in
return "Phone \(index):\(phone.value)"
}
I am trying to write a simple function that will check to see if a specific keyboard is installed.
Here is what I have in the function so far:
func isCustomKeyboardEnabled() {
let bundleID:NSString = "com.company.MyApp.Keyboard"
let installedKeyboards = NSUserDefaults.standardUserDefaults().objectForKey("AppleKeyboards")
println(installedKeyboards)
}
This is what it returns in the console:
Optional((
"en_GB#hw=British;sw=QWERTY",
"emoji#sw=Emoji",
"com.nuance.swype.app.Global-Keyboard",
))
I am having an hard time checking to see if my bundleID is in this returned object. I've tried a for in and anif(contains(x,x)) but it fails to build. Any help would be much appreciated.
Swift 2.0 Solution:
func installedKeyboards(){
if let installedKeyboard = NSUserDefaults.standardUserDefaults().objectForKey("AppleKeyboards") as? [String]{
if installedKeyboard.contains("Your Unique Identifier"){
print("Custom Keyboard Found")
}else{
print("Custom Keyboard Not Installed")
}
}
}
You've got an Optional response there, meaning that the value could be nil. Try doing this instead:
if let installedKeyboards = NSUserDefaults.standardUserDefaults().objectForKey("AppleKeyboards") {
if (contains(installedKeyboards, "Your keyboard") {
// Do stuff.
}
}
Here's the Swift 4 version from Statik answer:
func installedKeyboards() {
if let installedKeyboard = UserDefaults.standard.object(forKey: "AppleKeyboards") as? [String] {
if installedKeyboard.contains("Your Unique Identifier") {
print("Custom Keyboard Found")
}
else {
print("Custom Keyboard Not Installed")
}
}
}