Last active
August 29, 2015 14:03
-
-
Save dictav/fea0f4f5ae5b4740369f to your computer and use it in GitHub Desktop.
型クラスとかそんなの意識したけど結局できなかったもの
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
) | |
type Any interface{} | |
type Incrementer interface { | |
increment() Any | |
} | |
type myInt int | |
func (val myInt) increment() Any { | |
return val + 1 | |
} | |
type myString string | |
func (str myString) increment() Any { | |
return "incremented string" | |
} | |
func inc(val Incrementer) Any { | |
return val.increment() | |
} | |
func main() { | |
a := myInt(1) | |
fmt.Println(inc(a)) | |
b := myString("abc") | |
fmt.Println(inc(b)) | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import <Foundation.h> | |
@protocol Incremantable <NSObject> | |
- (instancetype)increment; | |
@end | |
@interface NSNumber(Incrementable)<Incremantable> @end | |
@implementation NSNumber (Incrementable) | |
- (instancetype)increment | |
{ | |
return @(self.integerValue + 1); | |
} | |
@end | |
@interface NSString (Incrementable) <Incremantable> @end | |
@implementation NSString (Incrementable) | |
- (instancetype)increment | |
{ | |
return @"incremented string"; | |
} | |
@end | |
id inc(id<Incremantable> value) { | |
return [value increment]; | |
} | |
int main(int argc, char * argv[]) | |
{ | |
@autoreleasepool { | |
NSLog(@"%@", inc(@1)); // 2 | |
NSLog(@"%@", inc(@"abc")); // incremented string | |
return 0; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
protocol Incrementable { | |
func increment() -> Self | |
} | |
func inc<T:Incrementable>(obj: T) -> T? { | |
let val = obj.increment() | |
return val | |
} | |
extension Int : Incrementable { | |
func increment() -> Int { | |
return self + 1 | |
} | |
} | |
extension String : Incrementable { | |
func increment() -> String { | |
var str = "" | |
for code in self.unicodeScalars { | |
str += String( UnicodeScalar(code.value + 1) ) | |
} | |
return str | |
} | |
} | |
inc(10) // 11 | |
inc("abc") // "bcd" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
発想が型クラスではないな