I need to gen several bools simultaneously - specman

I have:
struct MyStruct {
!Ipv4En : bool;
!Ipv6En : bool;
keep Ipv4En == TRUE or Ipv6En == TRUE;
MyMethod() is {
gen Ipv4En;
gen Ipv6En;
};
};
I always get Ipv4En TRUE, because those 2 bools are not generated together.
They can't be generated when I gen MyStruct.
How can I generate them together?
Meanwhile I patched it (don't like the solution):
I've deleted ! in the definition.
temp : MyStruct;
gen temp;
Ipv4En = temp.Ipv4En;
Ipv6En = temp.Ipv6En;

Since a gen action only takes a single gen-item, you have to group the two variables you want solved together. You can do this by defining a new struct:
struct IpVersionInfo {
Ipv4En: bool;
Ipv6En: bool;
keep Ipv4En == TRUE or Ipv6En == TRUE;
};
Instead of having two variables for your enables, you use a single variable of this new struct type:
struct MyStruct {
!ipVersionInfo: IpVersionInfo;
MyMethod() is {
gen ipVersionInfo;
};
};
If you run a couple of iterations, you'll see that you can reach all combinations:
extend sys {
run() is also {
for i from 1 to 20 {
var s: MyStruct = new;
s.MyMethod();
outf(
"Ipv4En = %s, Ipv6En = %s\n",
s.ipVersionInfo.Ipv4En,
s.ipVersionInfo.Ipv6En);
};
};
};
This requires an API change, though, so you'll need to update all code that referenced Ipv4En and Ipv6En.
Aside from grouping the two fields in a struct, there are also other ways of solving your problem. Another example would be to define an enum that contains values for your legal cases:
type ip_version_info_e: [ V4, V6, BOTH ];
As before, you can use a variable of this type in your struct:
struct MyStruct {
!ip_version_info: ip_version_info_e;
MyMethod() is {
gen ip_version_info;
};
};
If you run a couple of iterations of the new code you'll see that it also reaches all possible combinations:
extend sys {
run() is also {
for i from 1 to 20 {
var s: MyStruct = new;
s.MyMethod();
outf(
"Ipv4En = %s, Ipv6En = %s\n",
s.ip_version_info in [ V4, BOTH ],
s.ip_version_info in [ V6, BOTH ]);
};
};
};
Regardless of how you decide to solve the problem, you should hide the internal implementation from any client code that uses MyStruct. Notice that the out statements from above look different depending on how we chose to handle the IP version settings. Instead of having client code look too deep inside MyStruct you should define the following two methods:
isIpv4Enabled(): bool;
isIpv6Enabled(): bool;
In the case where we grouped the two Boolean variables in a struct, the implementations of these two methods are:
struct MyStruct {
// ...
isIpv4Enabled(): bool is {
result = ipVersionInfo.Ipv4En;
};
isIpv6Enabled(): bool is {
result = ipVersionInfo.Ipv6En;
};
};
In the case where we defined an enum, we have:
struct MyStruct {
// ...
isIpv4Enabled(): bool is {
result = ip_version_info in [ V4, BOTH ];
};
isIpv6Enabled(): bool is {
result = ip_version_info in [ V6, BOTH ];
};
};
In both cases, though, the client code for printing would be the same:
extend sys {
run() is also {
for i from 1 to 20 {
var s: MyStruct = new;
s.MyMethod();
outf(
"Ipv4En = %s, Ipv6En = %s\n",
s.isIpv4Enabled(),
s.isIpv4Enabled());
};
};
};
This is a major advantage. This way you are free to change your implementation of MyStruct in the future and not have to touch any other code that uses it.

Related

In Swift, how do I make a class's array of objects only accessible as an entire array?

I have a pattern that I want developers to be able to access my classes, due to using property observers. In the examples below, I have property observer on B.a and A.str, below, so if developers try modify B.a.str directly, only the str property observer is fired. So I want to limit access to B.a to only setting and getting the entire array, making modifications have to happen outside of access to B directly (i.e., you'll see below). I have been reading a lot of Apple docs on Swift 4+, and I can't figure it out. Example below:
class A
{
let str: String? = "Hello!"
...
}
class B
{
var a: [A]()
...
}
I don't want users to use this set of classes like this:
let b: B = B()
B.a.str? = "NewValue"
How do I make "a" accessible only by this pattern:
let a_ref = b.a
a_ref.str? = "NewValue"
b.a = a_ref
I am not sure why you want to have this pattern and I am not sure if it's a good idea to use it. Anyway, you can achieve what you want by simply returning a copy of a when you use the getter that B provides.
class A {
var str: String?
init(str: String? = "Hello") {
self.str = str
}
func copy() -> A {
return A(str: str)
}
}
class B {
private var _a = A()
var a: A {
get { return _a.copy() }
set { _a = newValue }
}
init() { }
}
Now you can test it with the following code:
// First Attempt (Direct)
let b: B = B()
b.a.str = "NewValue"
print(b.a.str) // Prints "Hello"
// Second Attempt (via Reference)
let a_ref = b.a
a_ref.str = "NewValue"
b.a = a_ref
print(b.a.str) // Prints "NewValue

Is a static boolean a reference type in Swift?

I'm making some switches. In my MenuScene class there's some booleans that are static variables, booleans, to represent the states of these switches.
Are these addressable as reference types, so I can be sure that other objects are able to change their state with a unique reference to them?
The dream, in my dreamy pseudo code, I'm hoping changes to iAmOn impact the state of myButtonABC_state
class MenuScene {
static var myButtonABC_state: Bool = false
static var myButtonXYZ_state: Bool = false
override onDidMoveToView {
let buttonABC = Button(withState: MenuScene.myButtonABC_state)
let buttonXYZ = Button(withState: MenuScene.myButtonXYZ_state)
}
}
In a button class
class Button {
var iAmOn: Bool = false
init(withState state: Bool){
iAmOn = state
}
override onTouchesBegun(... etc...){
if iAmOn { iAMOn = false }
else { iAmOn = true}
}
}
Bool is a struct in Swift; structs are value types. It doesn't matter if it's static var, class var, let, var, etc., the type is what matters--so no, Bool is value type.
I think you are not 100% on all of the terminology (mostly because Apple doesn't really cover it much in documentation as usual, lol).
There are "Swift Types" (Bool, Int, your classes/structs, etc), and "Variable/Constant Types" (which hold data in a memory register, such as references or actual-values), as well as "Memory Register Write/Read Types" (variable vs vonstant, mutable vs immutable, var vs let).
Don't be frustrated.. It's a bit confusing for everyone... Especially at first and without great documentation. (I tried learning C++ pointers early age and it was way over my head).
Here's a good reference material: (towards the bottom)
https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/ClassesAndStructures.html
Basically, if you want to hold a reference to something, you have to use a Reference Type memory register. This means using a class instance Static makes no difference:
/* Test1: */
struct Hi {
static var sup = "hey"
}
var z = Hi.sup
Hi.sup = "yo"
print(z) // prints "hey"
/* Test 2: */
class Hi2 {
static var sup = "hey"
}
var z2 = Hi2.sup
Hi2.sup = "yo"
print(z2) // Prints "hey"
If you feel like you need a pointer to something that isn't inside of a class, then you can use UnsafeMutablePointer or something like that from OBJc code.
Or, you can wrap a bool inside of a class object (which are always references).
final class RefBool {
var val: Bool
init(_ value: Bool) { val = value }
}
And here is some interesting behavior for reference types using let:
let someBool: RefBool
someBool = RefBool(true)
someBool = RefBool(false) // wont compile.. someBool is a `let`
someBool.val = false // will compile because of reference type and member is `var`

How do I declare, create, and use method pointers in Swift?

I'm not talking about pointers to C functions, but to a method within a Swift type.
struct Test: GeneratorType {
var methodPointer: mutating () -> Bool? // Non-working guess
var which: Bool
init() {
which = false
methodPointer = which ? &testMethod1 : &testMethod2 // Also non-working guess
}
//...
}
The compiler says "mutating" isn't legal as part of a function declaration. (Actually, it just suggests a semi-colon there.) And for the pointer initialization (after I remove mutating), the compiler thinks I'm trying to call the functions and use their results instead. I want to use the methods as objects in-and-of themselves here, not as a function call. Later on I want to use the pointed-to method within next; without figuring this out, I'll have to resort to an enumeration flag and manually choosing which method to call within next.
I hope there's some part of closure mechanics that allows this. Maybe something like this page, which describes functions returning functions. But none of the examples I've seen mention mutating methods.
See if this helps you.
class Something {
var f: ( () -> Int )?
let f1 = { () -> Int in /* do some action here */ return 1}
let f2 = { () -> Int in /* do some action here */ return 2}
func ff(which: Bool) {
f = which ? f1 : f2
}
func act() {
if let f = f {
f()
}
}
}
Here is how I do it -
class FcnArgs { //#goal pass a fcn as arg
class func demo() {
let fPtr = funcToPointTo; //#type '((Int)->String)'
print(fPtr(4));
}
class func funcToPointTo(_ i : Int) -> String {
print("I Was passed \(i)");
return "I was returned";
}
}
FcnArgs.demo() output:
I Was passed 4
I was returned

Swift SpriteKit use struct instead of class to render sprites

I have been updating my game recently to use more value types. I am still not 100% confident with weak and unowned in some cases so I went the struct way to avoid strong reference cycles. As per apples newer keynotes it seems value types are they way to go for the most part anyway.
I have never seen an example where structs are used to render sprites in a spriteKit game so I wonder what the drawbacks are.
I understand that they are copied and not referenced but for my usage it seems to work.
So basically is there something I need to watch out for when doing this
struct Flag {
let post: SKSpriteNode
let flag: SKSpriteNode
init(postImage: String, flagImage: String) {
post = SKSpriteNode(imageNamed: postImage)
// other set ups for post sprite
flag = SKSpriteNode(imageNamed: flagImage)
// other set ups for flag sprite
post.addChild(flag)
}
func animate() {
// code to animate flag
}
}
Than in my SKScenes I simply add them as usual
let flag = Flag(postImage: "FlagPostImage", flagImage: "FlagImage")
flag.post.position = ...
addChild(flag.post)
flag.animate()
Now even if I create multiple flags in the same scene I seem to have no problems with this way.
I am just curious because I have never really seen an example like this so I wonder if I am missing something, like performance drawbacks etc.
Thanks for any help.
Personally I avoid creating Structs that contain Classes. Because Structs copy, each and every copy that get's passed around your app will increase the reference count of the Classes. This makes it harder to manage them instead of easier.
It is also useful to take a look at how UIKit uses Structs. A UIView is an object but has many defining properties that are Structs. For example it's frame.
Drop the code below in a playground to see some effects of this behaviour.
The protocol is just to get some meaningful feedback form the playground.
protocol IDLookable : CustomPlaygroundQuickLookable {
var id : Int { get set }
}
extension IDLookable {
func customPlaygroundQuickLook() -> PlaygroundQuickLook {
return PlaygroundQuickLook.AttributedString(NSAttributedString(string: "\(self.dynamicType) with id : \(self.id)"))
}
}
class MyClass : IDLookable {
var id : Int = 0
init(id : Int) {
self.id = id
}
}
struct MyContainerStruct : IDLookable {
var id : Int = 0
var object : MyClass
init(id : Int, object:MyClass) {
self.id = id
self.object = object
}
}
class Scope {
// ref count = 1
var object = MyClass(id: 11)
var structContainer : MyContainerStruct
init() {
// ref count = 2
structContainer = MyContainerStruct(id: 222, object: object)
messWithAClassInAStruct()
}
func messWithAClassInAStruct() {
// ref count = 3
var structContainerTwo = structContainer
structContainerTwo.id = 333
structContainerTwo.object // 11
// altering the object in one struct will obvously update all references
structContainerTwo.object.id = 1
structContainer.object // 1
structContainerTwo.object // 1
}
}
let test = Scope()
One pattern that does make it easy to work with Reference Types in Value Types is to store them as weak optionals in the Value Types. This means that something will need to have a strong reference but chances are that some Class will be responsible for creating the Structs this is a good place to keep that strong reference.
struct MyContainerStruct : IDLookable {
var id : Int = 0
weak var object : MyClass?
init(id : Int, object:MyClass) {
self.id = id
self.object = object
}
}
class Scope {
// ref count = 1
var object = MyClass(id: 11)
var structContainer : MyContainerStruct
init() {
// ref count = 1
structContainer = MyContainerStruct(id: 222, object: object)
messWithAClassInAStruct()
}
func messWithAClassInAStruct() {
// ref count = 1
var structContainerTwo = structContainer
structContainerTwo.id = 333
structContainerTwo.object // 11
}
}
let test = Scope()

UnityScript, print in constructor + non-var variable doesn't work

When I try to create an instance of Monster class the print function doesn't seem to do anything. Why is that? I'm working with unity 4 if that's of any help. Also I cannot make a Monster class instance without using var, despite it being optional(allegedly).
function Update () {
var mon = Monster("Torreadore");
mon2 = Monster("blueberry"); //unknown identifier : 'mon2'
//even though it's been said that var is optional in the js tutorial
}
class Monster
{
var name : String;
function Monster(n : String)
{
name = n;
print(name + " has been created.");
}
}