How do I declare typedef in Swift - typedef

If I require a custom type in Swift, that I could typedef, how do I do it? (Something like a closure syntax typedef)

The keyword typealias is used in place of typedef:
typealias CustomType = String
var customString: CustomType = "Test String"

added to the answer above:
"typealias" is the keyword used is swift which does similar function as typedef.
/*defines a block that has
no input param and with
void return and the type is given
the name voidInputVoidReturnBlock*/
typealias voidInputVoidReturnBlock = () -> Void
var blockVariable :voidInputVoidReturnBlock = {
println(" this is a block that has no input param and with void return")
}
To create a typedef with input param the syntax is as shown below :
/*defines a block that has
input params NSString, NSError!
and with void return and the type
is given the name completionBlockType*/
typealias completionBlockType = (NSString, NSError!) ->Void
var test:completionBlockType = {(string:NSString, error:NSError!) ->Void in
println("\(string)")
}
test("helloooooooo test",nil);
/*OUTPUTS "helloooooooo test" IN CONSOLE */

Related

How to initialize and use function pointer in Swift

Let's say I have this code snipped in the playground
import UIKit
internal final class TestClass {
internal final var funcPointer: () -> Void
init() {
self.funcPointer = self.func1() //Cannot assign value of type '()' to type '() -> Void'
}
internal final func func1() {
print("func1 is called!")
}
}
var testClass: TestClass = TestClass()
testClass.funcPointer()
Why do I get the shown error message within the init() method and how to initialize a function pointer correctly?
I have already seen this SO post and this tutorial but anyway I don't get it to work for a (Void) -> Void function...
To assign the closure to the property you have to remove the parentheses
self.funcPointer = self.func1
The subsequent error
self' used in method call 'func1' before all stored properties are initialized
can be fixed by declaring funcPointer implicit unwrapped optional
internal final var funcPointer: (() -> Void)!

Enum parameter for function

enum FooEnum: Int {
case fooEnumCase = 13512
case fooEnumCase2 = 425156
}
class FooClass {
public func myFunction(chosenEnumCase: fooEnum) -> String {
/* Logic */
}
}
fooClass.myFunction(fooEnum.fooEnumCase)
I am getting the error:
FooEnum is not convertible to FooClass
What is wrong with this code?
First of all the code is very hard to read with lowercase class names.
Two issues:
With this syntax the method is supposed to be a class function.
public static func myFunction(chosenEnumCase: FooEnum) -> String
Which raises a new error
Missing argument label 'chosenEnumCase:' in call
and you have to add the parameter label:
enum FooEnum: Int {
case fooEnumCase = 13512
case fooEnumCase2 = 425156
}
class FooClass {
public static func myFunction(chosenEnumCase: FooEnum) -> String {
//logic
}
}
FooClass.myFunction(chosenEnumCase: FooEnum.fooEnumCase)
To explain the error message let's consider fooClass.myFunction:
let f: (fooClass) -> ((fooEnum) -> String) = fooClass.myFunction
It's a function that expects an instance of fooClass, and returns another function ((fooEnum) -> String). Whereas in your code it is fed an instance of type fooEnum.
Call that function on a instance:
let myInstance = fooClass()
myInstance.myFunction(chosenEnumCase: fooEnum.fooEnumCase)
Or make myFunction a class function:
public class func myFunction(chosenEnumCase: fooEnum) -> String
PS: To conform to the Swift naming conventions use FooEnum and FooClass.

Type override in generic protocol giving "explicitly specify the generic arguments to fix this issue" error

I am trying to change the default associated type to String. but getting this error
explicitly specify the generic arguments to fix this issue.
Below code works fine for type Int but not for String. Am i missing something?
//override/Change the associated Type of Protocol
protocol Familiable{
associatedtype FamilyType = Int
func getName()->[FamilyType]
}
class NumberFamily:Familiable{
func getName() -> [Int] {
return [1,2,3,4,5]
}
}
let numRef = NumberFamily()
print(numRef.getName())
type(of: numRef)
struct NormalFamily<T:ExpressibleByStringLiteral>: Familiable{
func getName() -> [T] {
return ["name1","name2"]
}
}
let normalRef = NormalFamily()
normalRef.getName()

Swift playground and LeetCode OJ

class Solution {
func reverseString(s: String) -> String {
let rev = String(s.characters.reverse())
print(rev)
}
}
The error i get is:
Missing return in a function expected to return String
The same function in Leetcode OJ gives me the following error:
Line 4: cannot call value of non-function type 'Distance' (aka 'Int')
While i type the following in the Playground it works fine:
var str = "Hello"
let rev = String(str.characters.reverse())
I can't seem to figure out the solution to this and why it behaves differently in the playground with the function return type and in Leetcode OJ.
Swift noob and any help would be most appreciated! thanks
Try this:
class Solution {
func reverseString(s: String) -> String {
let rev = String(s.characters.reverse())
print(rev)
return rev
}
}
var str = Solution()
str.reverseString("Hello")
If you intend to add custom methods which works on a a particular Type than create an extension on that Type type.
extension String {
// you methods
}
For example:
extension String {
func length() -> Int {
return self.characters.count
}
}
Then you can use it as class function on String type
let greetings: String = "Hello"
greetings.length() // 5

cannot convert expression type void to type integer in Swift using XCTAssertEqual

I am very new to the Swift language and XCode. Have a error message from this code:
Class Deck
class Deck {
var decks : Integer = 0
init () {
decks = 1
}
init (amountOfDecks : Integer){
decks = amountOfDecks
}
func getAmountOfCards() -> Integer {
return 0
}
}
Test Class
import XCTest
import helloWorldv2
class helloWorldv2Tests: XCTestCase {
override func setUp() {
super.setUp()
}
override func tearDown() {
super.tearDown()
}
func testDeckConstructor() {
var deck = Deck(amountOfDecks: 1)
var amount : Integer = deck.getAmountOfCards()
let expected : Integer = 52
// ERROR: Cannot convert the expression type 'void' to type 'integer'
XCTAssertEqual(expected, amount)
}
}
I set the two variables to type Integer so don't understand why I cant compare the two values...
the Type you should be using is Int (Integer is a protocol, not a Type, and there is not an implementation in Swift for == that accepts arguments conforming to the Integer protocol)
specifying the Type in the way that you are doing it is unnecessary, thanks to Swift's "type inference" - when you declare and assign a value to a variable, it will automatically give that variable the same Type as the value that is being assigned to it (and literal integers in Swift are typed as Int by default)... so let expected = 52 will automatically give your expected constant the Type Int without you having to declare it as such
Integer is a protocol, you should use Int instead as that is an actual struct.