xcode issue with apple swift [duplicate] - ios

This question already has answers here:
SourceKitService Terminated
(34 answers)
Closed 8 years ago.
I was testing swift language.
Suddenly xcode terminated without showing error.
But got the following message:
Source kit service terminated editor functionality temporarily limited
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.myfunction()
//ViewController.classFunc()
//myfunctionWithArg()
//myfunctionWithArg(name: "hashim")
//learnSwitch()
self.learnClosure()
/*
let anInstance = MyClass()
anInstance.aFunction()
let someVehicle = Vehicle()
println(someVehicle.description)
someVehicle.description = "test"
let aCycle = Cycle()
println(aCycle.description)
*/
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func learnClosure(){
let retValue = jediGreet("old friend")
println(retValue)
println(retValue.0)
println(retValue.1)
let train = jediTrainer("hashim")
println(train("new programming swift", 3))
println((jediTrainer("hashim"))("Obi Wan", 3))
var names = ["fashim","hashim","ashim","bashim","cashim","dashim"]
sort(names, { (s1:String,s2:String)-> Bool in
println("test arg1:\(s1), arg2:\(s2)")
return s1>s2 } )
sort(names, >)
println(sort(names, <))
/*
let myadd = { (sum:Int,number:Int)->Int in
return (sum + number)
}
*/
// let myadd = { ($0 + $1) }
// println("sum is \(myadd(3,4))")
let padawans = ["Knox", "Avitla", "Mennaus"]
println( padawans.map({
(padawan: String) -> String in
"\(padawan) has been trained!"
}))
var numbers = [10,1,20,123,50]
println("before \(numbers)")
mySort(numbers,{
(num1:Int,num2:Int) -> Bool in
return num1 > num2
})
println("after \(numbers)")
}
func mySort( numbers:Int[],compare:((Int,Int)->Bool))
{
//Write your login to sort numbers using comparator method
var tmp:Int
var n = numbers.count
for(var i=0;i<n;i++)
{
for(var j=0;j<n-i-1;j++)
{
if(numbers[j] > numbers[j+1])
{
tmp=numbers[j];
numbers[j]=numbers[j+1];
numbers[j+1]=tmp;
}
}
}
}
func repeat (count:Int,task:()->()){
for i in 0..count{
task()
}
}
func jediGreet(String) -> (farewell: String, mayTheForceBeWithYou: String) {
return ( "name" , " May the (ability) be with you.")
}
func jediTrainer (caller:String) -> ((String, Int) -> String) {
func train(name: String, times: Int) -> (String) {
return "\(name) has been trained in the Force \(times) times calling \(caller)"
}
return train
}
}

This can happen due to several reason in xcode (it is just because swift is still in beta) . In your case just comment the line // println(train("new programming swift", 3)). If you want to get this functionality split that line of code into two

Related

FBSnapshotTestCase does not create the FB_REFERENCE_IMAGE_DIR and IMAGE_DIFF_DIR folders

this is my test :
class ZabiTests: FBSnapshotTestCase {
var vc:UIViewController?
override func setUpWithError() throws {
super.setUp()
vc = ViewController()
recordMode = true
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() throws {
FBSnapshotVerifyView((vc?.view)!)
}
func testPerformanceExample() throws {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
first time i run with recordMode = true and then i run without this line, and still i get Snapshot comparison failed
(vc is okey, red background and not nil )
After playing around with it I created an alternative way of auto defining those folders by creating my own base class:
open class MySnapshotTestCase: FBSnapshotTestCase {
var referenceImageDirectory: String?
var imageDiffDirectory: String?
public func verify(
view: UIView,
file: StaticString = #file,
line: UInt = #line
) {
let directory = ("\(file)" as NSString).deletingLastPathComponent
// Save for later use in getReferenceImageDirectory
referenceImageDirectory = NSString.path(withComponents: [directory, "ReferenceImages"])
// Save for later use in getImageDiffDirectory
imageDiffDirectory = NSString.path(withComponents: [directory, "FailedSnapshotTests"])
FBSnapshotVerifyView(
view,
identifier: nil,
perPixelTolerance: 0,
overallTolerance: 0,
file: file,
line: line)
}
open override func getReferenceImageDirectory(withDefault dir: String?) -> String {
guard let referenceImageDirectory = referenceImageDirectory else {
fatalError("Do not call FBSnapshotVerifyView directly, use WazeSnapshotTestCase.verify instead.")
}
return referenceImageDirectory
}
open override func getImageDiffDirectory(withDefault dir: Swift.String?) -> Swift.String {
guard let imageDiffDirectory = imageDiffDirectory else {
fatalError("Do not call FBSnapshotVerifyView directly, use WazeSnapshotTestCase.verify instead.")
}
return imageDiffDirectory
}
}

CMSensorDataList enumeration in swift on ios11

There are a number of discussions about enumerating through CMSensorDataList around, however, they all have the same example:
extension CMSensorDataList: SequenceType {
public func generate() -> NSFastGenerator {
return NSFastGenerator(self)
}
}
Which doesn't work on ios11 for multiple reasons (NSFastGenerator doesn't exist, SequenceType has been renamed to Sequence).
How do I enumerate through a CMSensorDataList in modern swift?
if swift 4 and 5 it will work
extension CMSensorDataList: Sequence {
public typealias Iterator = NSFastEnumerationIterator
public func makeIterator() -> NSFastEnumerationIterator {
return NSFastEnumerationIterator(self)
}
}
now you will need to do like blow
let rec = CMSensorRecorder()
if let list = rec.accelerometerData(from: date1, to: date2) {
for item in list {
if let data = item as? CMRecordedAccelerometerData {
let x = data.acceleration.x
print("X: \(x)")
}
}
}

Swift app for solving factors of numbers and display

i'm new the forum and also new to the swift language. I've been playing around with xcode and wanted to create an app that uses a fenceloop to display the factors of a number as a "solution." The app currently uses a label to display, a text for input, and a button to initiate. I have what i think to be functioning code but i can't see to get it to work because from what i understand, i have to convert the input that's a string into an int. If anyone has any ideas how to get this working; since i feel like i've done what i can.
The problem in particular i am getting is it is saying that "Cannot convert value of type 'UITextField!; to expected argument type 'Int'. What i intend to happen is that on the button click, it solves for the factors of whatever is in the text box and displays it as a string in the label. Any help is appreciated!
import UIKit
class ViewController: UIViewController {
#IBOutlet var input1 : UITextField!
#IBOutlet var label : UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
#IBAction func printFactors(n: Int) {
var result: String = ""
for i in 1...n {
guard n % i == 0 else {continue}
result += i == 1 ? "1" : " and \(i)"
}
print(result)
let outputText = printFactors(n: input1)
label.text = outputText
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
You have a lot of issues and confusion in your printFactors method. Lets split it up and setup things properly.
First, make a separate method to do the math:
func calculateFactors(n: Int) -> String {
var result: String = ""
for i in 1...n {
guard n % i == 0 else {continue}
result += i == 1 ? "1" : " and \(i)"
}
print(result)
return result
}
Now lets setup the button action:
#IBAction func factorAction(sender: UIButton) {
if let text = input1.text {
if let num = Int(text) {
let factor = calculateFactors(n: num)
label.text = factor
} else {
// Show the user that the entered text isn't a number
}
} else {
// There's no text
}
}
Setup your button to use the new factoryAction: method instead of the old printFactors: method.
Swift 3
Can reduce this code down to two lines with some functional magic.
func factors(of number: Int) -> [Int] {
return (1...number).filter { number % $0 == 0 }
}
print(factors(of: 24))

Can i have 2 types on parameter in swift?

so i've created function and it does something, but i want it to do something else if the parameter type is different, for example:
func (parameter: unknownType){
if(typeof parameter == Int){
//do this
}else if(typeof parameter == String){
//do that
}
}
i've done this in javascript or other programming languages, but i don't know how to do this in swift
i've created function which takes 1 argument UITextField and centers it using constraints
now i want to center my button, but since button is not UITextField type it does not work, so is there a way i can tell function to do the same on UIButton??
Use Overload:
class Example
{
func method(a : String) -> NSString {
return a;
}
func method(a : UInt) -> NSString {
return "{\(a)}"
}
}
Example().method("Foo") // "Foo"
Example().method(123) // "{123}"
The equivalent of the Javascript code would be:
func doSomething(parameter: Any?) {
if let intValue = parameter as? Int {
// do something with the int
} else if let stringValue = parameter as? String {
// do something with the string
}
}
But be warned, this approach makes you loose the type safety which is one of most useful feature of Swift.
A better approach would be to declare a protocol that is implemented by all types that you want to allow to be passed to doSomething:
protocol MyProtocol {
func doSomething()
}
extension Int: MyProtocol {
func doSomething() {
print("I am an int")
}
}
extension String: MyProtocol {
func doSomething() {
print("I am a string")
}
}
func doSomething(parameter: MyProtocol) {
parameter.doSomething()
}
doSomething(1) // will print "I am an int"
doSomething("a") // will print "I am a string"
doSomething(14.0) // compiler error as Double does not conform to MyProtocol
It can
Sample code:
func temFunc(obj:AnyObject){
if let intValue = obj as? Int{
print(intValue)
}else if let str = obj as? String{
print(str)
}
}
You can make use of Any and downcasting:
func foo(bar: Any){
switch(bar) {
case let a as String:
/* do something with String instance 'a' */
print("The bar is a String, bar = " + a)
case let a as Int:
/* do something with Int instance 'a' */
print("The bar is an Int, bar = \(a)")
case _ : print("The bar is neither an Int nor a String, bar = \(bar)")
}
}
/* Example */
var myString = "Hello"
var myInt = 1
var myDouble = 1.5
foo(myString) // The bar is a String, bar = Hello
foo(myInt) // The bar is an Int, bar = 1
foo(myDouble) // The bar is neither an Int nor a String, bar = 1.5
Check this solution:
https://stackoverflow.com/a/25528882/256738
You can pass an object AnyObject and check the class in order to know what kind of object it is.
UPDATE
Good point #Vojtech Vrbka
Here an example:
let x : AnyObject = "abc"
switch x {
case is String: println("I'm a string")
case is Array: println("I'm an Array")
// Other cases
default: println("Unknown")
}

Swift error: Initializer for conditional binding must have Optional type, not '()'

I'm doing the course of iTunes University called "Developing iOS 8 Apps with Swift". On the third video I encountered with a problem that did not happen in the video, even though it was the same code, that is as follows:
class ViewController: UIViewController{
…
#IBAction func operate(sender: UIButton) {
if userIsInTheMiddleOfTypingANumber{
enter()
}
if let operation = sender.currentTitle {
if let result = brain.performOperation(operation) { > ERROR HERE
displayValue = result
} else {
displayValue = 0
}
}
}
…
}
After reading many explanations of this error I suppose the problem comes from here:
class CalculatorBrain
{
…
func performOperation(symbol: String) {
if let operation = knownOps[symbol] { opStack.append(operation)
}
}
}
Thank you if you can help me!
performOperation doesn't return anything and needs to return an optional type so that it can be used in your if let statement (to check if it did indeed return a value) and that's what it could be moaning about.
Try:
func performOperation(symbol: String) -> Int? {
which means it could return an Int, and then your if let statement should be happy.

Resources