我正在尝试将Objective C应用程序转换为Swift。我有一节课:
@interface XYUser : NSObject
@property (nonatomic, retain) NSString *name;
@property (nonatomic, retain) NSString *bio;
+ (XYUser)currentUser;
@end
然后我有一个实现:
@implementation XYUser
+ (XYUser)currentUser {
XYUser *user = [[XYUser alloc] init];
user.name = @"Bob Jim";
user.bio = @"Hey all, I like to program!";
return user;
}
@end
我怎么能在swift中这样做?我希望能够XYUser.currentuser()
或能够创建一个像:
var jim = XYUser()
jim.name = "Jim"
答案 0 :(得分:2)
将代码转换为Swift时,需要考虑以下几点提示:
最简单的解决方案是:
struct User {
var name: String
var bio: String
static func currentUser() -> User {
let user = User(name: "Sam", bio: "I'm sam")
return user
}
}
extension User {
init() {
name = ""
bio = ""
}
}
// Use example
var user = User(name: "Sam", bio: "I'm sam")
user.name = "Jim"
var current = User.currentUser()
var empty = User()
empty.name = "Lolly"